]> cloudbase.mooo.com Git - z180-stamp.git/blame_incremental - avr/cmd_attach.c
reset optind before executing command
[z180-stamp.git] / avr / cmd_attach.c
... / ...
CommitLineData
1/*
2 * (C) Copyright 2016 Leo C. <erbl259-lmu@yahoo.de>
3 *
4 * SPDX-License-Identifier: GPL-2.0
5 */
6
7/*
8 * attach channels to devices
9 */
10
11#include "cmd_attach.h"
12
13#include "command.h"
14#include "z180-serv.h"
15#include "getopt-min.h"
16
17
18/*
19 * attach [[options] [unit [diskfile]]]
20 *
21 * detach unit
22 * attach -d unit
23 *
24 * attach -o reattach unit
25 * attach -o reattach unit diskfile
26 *
27 * attach unit diskfile
28 *
29 */
30
31command_ret_t do_attach(cmd_tbl_t *cmdtp, uint_fast8_t flag, int argc, char * const argv[])
32{
33 uint8_t unit = 0;
34 char *filename = NULL;
35 bool detach = false;
36 bool detach_all = false;
37 drv_opt_t options = 0;
38 int res;
39
40 (void) cmdtp; (void) flag;
41
42
43 if (argv[0][0] == 'd') {
44 /* we are called as 'detach' */
45 detach = true;
46 } else if (argc == 1) {
47 /* no arguments */
48 drv_list();
49 return CMD_RET_SUCCESS;
50 }
51
52 int opt;
53 while ((opt = getopt(argc, argv, PSTR("darwo:"))) != -1) {
54 switch (opt) {
55 case 'd':
56 detach = true;
57 break;
58 case 'a':
59 detach_all = true;
60 break;
61 case 'r':
62 options |= DRV_OPT_RO;
63 break;
64 case 'w':
65 options &= ~DRV_OPT_RO;
66 break;
67 case 'o':
68 {
69 static const FLASH char delim[] = {", "};
70 char *p = strtok_P(optarg, delim);
71 while (p != NULL) {
72 if (!strcmp_P(p, PSTR("ro")))
73 options |= DRV_OPT_RO;
74 else if (!strcmp_P(p, PSTR("rw")))
75 options &= ~DRV_OPT_RO;
76 else if (!strcmp_P(p, PSTR("debug")))
77 options |= DRV_OPT_DEBUG;
78 else if (!strcmp_P(p, PSTR("nodebug")))
79 options &= ~DRV_OPT_DEBUG;
80 else if (!strcmp_P(p, PSTR("reattach")))
81 options |= DRV_OPT_REATTATCH;
82 else
83 return CMD_RET_USAGE;
84
85 p = strtok_P(NULL, delim);
86 }
87 }
88 break;
89 default: /* '?' */
90 return CMD_RET_USAGE;
91 }
92 }
93
94 /* remaining arguments */
95 argc -= optind;
96 if ( !( (argc == 0 && detach && detach_all) ||
97 (argc == 1 && detach) ||
98 (argc == 1 && (options & DRV_OPT_REATTATCH)) ||
99 argc == 2) )
100 return CMD_RET_USAGE;
101
102 if (argc > 0 && ((strlen(argv[optind]) != 4) ||
103 strncmp_P(argv[optind], PSTR("dsk"), 3) ||
104 (unit = argv[optind][3] - '0') >= CONFIG_CPM_MAX_DRIVE)) {
105
106 cmd_error(CMD_RET_FAILURE, 0, PSTR("Invalid device: '%s'"), argv[optind]);
107 }
108
109 if (detach) {
110 if (detach_all)
111 for (uint8_t i = 0; i < CONFIG_CPM_MAX_DRIVE; i++)
112 drv_detach(i);
113 else
114 drv_detach(unit);
115 return CMD_RET_SUCCESS;
116 }
117
118 if (argc == 2)
119 filename = argv[++optind];
120
121 res = drv_attach(unit, filename, options);
122 if (res)
123 cmd_error(CMD_RET_FAILURE, res, PSTR("Attachment of '%s' to dsk%d failed"), filename, unit);
124
125 return CMD_RET_SUCCESS;
126}