loop device code: readability improvement
[oweals/busybox.git] / util-linux / losetup.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * Mini losetup implementation for busybox
4  *
5  * Copyright (C) 2002  Matt Kraai.
6  *
7  * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
8  */
9
10 #include <getopt.h>
11 #include <stdlib.h>
12
13 #include "busybox.h"
14
15 int losetup_main(int argc, char **argv);
16 int losetup_main(int argc, char **argv)
17 {
18         unsigned opt;
19         char *opt_o;
20         unsigned long long offset = 0;
21
22         opt = getopt32(argc, argv, "do:", &opt_o);
23         argc -= optind;
24         argv += optind;
25
26         if (opt == 0x3) // -d + -o (illegal)
27                 bb_show_usage();
28
29         if (opt == 0x1) { // -d
30                 /* detach takes exactly one argument */
31                 if (argc != 1)
32                         bb_show_usage();
33                 if (!del_loop(argv[0]))
34                         return EXIT_SUCCESS;
35                 bb_perror_nomsg_and_die();
36         }
37
38         if (opt == 0x2) // -o
39                 offset = xatoull(opt_o);
40
41         /* -o or no option */
42
43         if (argc == 2) {
44                 if (set_loop(&argv[0], argv[1], offset) < 0)
45                         bb_perror_nomsg_and_die();
46         } else if (argc == 1) {
47                 char *s = query_loop(argv[0]);
48                 if (!s)
49                         bb_perror_nomsg_and_die();
50                 printf("%s: %s\n", argv[0], s);
51                 if (ENABLE_FEATURE_CLEAN_UP)
52                         free(s);
53         } else {
54                 char dev[sizeof(LOOP_NAME"0")] = LOOP_NAME"0";
55                 char c;
56                 for (c = '0'; c <= '9'; ++c) {
57                         char *s;
58                         dev[sizeof(LOOP_NAME"0")-2] = c;
59                         s = query_loop(dev);
60                         if (s) {
61                                 printf("%s: %s\n", dev, s);
62                                 if (ENABLE_FEATURE_CLEAN_UP)
63                                         free(s);
64                         }
65                 }
66         }
67         return EXIT_SUCCESS;
68 }