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
12#include "libbb.h"
13
14int losetup_main(int argc, char **argv);
15int losetup_main(int argc, char **argv)
16{
17	unsigned opt;
18	char *opt_o;
19	unsigned long long offset = 0;
20
21	opt = getopt32(argv, "do:", &opt_o);
22	argc -= optind;
23	argv += optind;
24
25	if (opt == 0x3) // -d + -o (illegal)
26		bb_show_usage();
27
28	if (opt == 0x1) { // -d
29		/* detach takes exactly one argument */
30		if (argc != 1)
31			bb_show_usage();
32		if (!del_loop(argv[0]))
33			return EXIT_SUCCESS;
34		bb_perror_nomsg_and_die();
35	}
36
37	if (opt == 0x2) // -o
38		offset = xatoull(opt_o);
39
40	/* -o or no option */
41
42	if (argc == 2) {
43		if (set_loop(&argv[0], argv[1], offset) < 0)
44			bb_perror_nomsg_and_die();
45	} else if (argc == 1) {
46		char *s = query_loop(argv[0]);
47		if (!s)
48			bb_perror_nomsg_and_die();
49		printf("%s: %s\n", argv[0], s);
50		if (ENABLE_FEATURE_CLEAN_UP)
51			free(s);
52	} else {
53		char dev[sizeof(LOOP_NAME"0")] = LOOP_NAME"0";
54		char c;
55		for (c = '0'; c <= '9'; ++c) {
56			char *s;
57			dev[sizeof(LOOP_NAME"0")-2] = c;
58			s = query_loop(dev);
59			if (s) {
60				printf("%s: %s\n", dev, s);
61				if (ENABLE_FEATURE_CLEAN_UP)
62					free(s);
63			}
64		}
65	}
66	return EXIT_SUCCESS;
67}
68