blob: 82723fd32dc677af3b57d05865625364e0acbbf9 [file] [log] [blame]
Nico Huber589cea62023-02-11 18:01:26 +01001/*
2 * This file is part of the flashprog project.
3 *
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 */
14
15#include <stdio.h>
16#include <stdlib.h>
17#include <string.h>
18
19#include "flash.h"
20#include "cli.h"
21
22static const char *const command_prefix = "flashprog-";
23
24static const struct {
25 const char *name;
26 int (*main)(int argc, char *argv[]);
27} commands[] = {
28 { "mem", flashprog_classic_main },
29 { "memory", flashprog_classic_main },
30};
31
32static void usage(const char *const name)
33{
34 fprintf(stderr, "\nUsage: %s [<command>] [<argument>...]\n", name);
35 fprintf(stderr, "\nWhere <command> can be\n\n"
36 " mem[ory] Standard memory operations\n"
37 " (read/erase/write/verify)\n"
38 "\n"
39 "The default is 'memory'. See `%s <command> --help`\n"
40 "for further instructions.\n\n", name);
41 exit(1);
42}
43
44static int combine_argv01(char *argv[])
45{
46 const size_t len = strlen(argv[0]) + 1 + strlen(argv[1]) + 1;
47 char *const argv0 = malloc(len);
48 if (!argv0) {
49 fprintf(stderr, "Out of memory!\n");
50 return 1;
51 }
52 snprintf(argv0, len, "%s %s", argv[0], argv[1]);
53 argv[1] = argv0;
54 return 0;
55}
56
57int main(int argc, char *argv[])
58{
59 const char *cmd;
60 size_t i;
61
62 print_version();
63 print_banner();
64
65 if (argc < 1)
66 usage("flashprog");
67
68 /* Turn something like `./flashprog-cmd` into `flashprog-cmd`: */
69 const char *const slash = strrchr(argv[0], '/');
70 if (slash)
71 cmd = slash + 1;
72 else
73 cmd = argv[0];
74
75 /* Turn `flashprog-cmd` into `cmd`: */
76 if (!strncmp(cmd, command_prefix, strlen(command_prefix)))
77 cmd += strlen(command_prefix);
78
79 /* Run `cmd` if found: */
80 for (i = 0; i < ARRAY_SIZE(commands); ++i) {
81 if (!strcmp(cmd, commands[i].name))
82 return commands[i].main(argc, argv);
83 }
84
85 if (argc < 2)
86 usage(argv[0]);
87
88 /* Try to find command as first argument in argv[1]: */
89 for (i = 0; i < ARRAY_SIZE(commands); ++i) {
90 if (!strcmp(argv[1], commands[i].name)) {
91 /* Squash argv[0] into argv[1]: */
92 if (combine_argv01(argv))
93 return 1;
94 return commands[i].main(argc - 1, argv + 1);
95 }
96 }
97
98 /* We're still here? Fall back to classic cli: */
99 return flashprog_classic_main(argc, argv);
100}