af0b03a5326f74d0fb3f64e78b210db5e41c147c
[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 {
17         unsigned long opt;
18         char *opt_o;
19         int offset = 0;
20
21         opt = bb_getopt_ulflags(argc, argv, "do:", &opt_o);
22         argc -= optind;
23         argv += optind;
24
25         if (opt == 0x3) bb_show_usage(); // -d and -o (illegal)
26
27         if (opt == 0x1) { // -d
28                 /* detach takes exactly one argument */
29                 if (argc != 1)
30                         bb_show_usage();
31                 if (!del_loop(argv[0]))
32                         return EXIT_SUCCESS;
33                 bb_perror_nomsg_and_die();
34         }
35
36         if (opt == 0x2) // -o
37                 offset = bb_xparse_number(opt_o, NULL);
38
39         /* -o or no option */
40
41         if (argc == 2) {
42                 if (set_loop(&argv[0], argv[1], offset) < 0)
43                         bb_perror_nomsg_and_die();
44         } else if (argc == 1) {
45                 char *s = query_loop(argv[0]);
46                 if (!s) bb_perror_nomsg_and_die();
47                 printf("%s: %s\n", argv[0], s);
48                 if (ENABLE_FEATURE_CLEAN_UP) free(s);
49         } else
50                 bb_show_usage();
51         return EXIT_SUCCESS;
52 }