1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <getopt.h>
4
5 #include "main-func.h"
6 #include "udev-util.h"
7
8 static bool arg_verbose = false;
9
help(void)10 static void help(void) {
11 printf("%s\n\n"
12 "Report whether we are connected to an external power source.\n\n"
13 " -h --help Show this help\n"
14 " --version Show package version\n"
15 " -v --verbose Show state as text\n",
16 program_invocation_short_name);
17 }
18
parse_argv(int argc,char * argv[])19 static int parse_argv(int argc, char *argv[]) {
20
21 enum {
22 ARG_VERSION = 0x100,
23 };
24
25 static const struct option options[] = {
26 { "help", no_argument, NULL, 'h' },
27 { "version", no_argument, NULL, ARG_VERSION },
28 { "verbose", no_argument, NULL, 'v' },
29 {}
30 };
31
32 int c;
33
34 assert(argc >= 0);
35 assert(argv);
36
37 while ((c = getopt_long(argc, argv, "hv", options, NULL)) >= 0)
38
39 switch (c) {
40
41 case 'h':
42 help();
43 return 0;
44
45 case ARG_VERSION:
46 return version();
47
48 case 'v':
49 arg_verbose = true;
50 break;
51
52 case '?':
53 return -EINVAL;
54
55 default:
56 assert_not_reached();
57 }
58
59 if (optind < argc)
60 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
61 "%s takes no arguments.",
62 program_invocation_short_name);
63
64 return 1;
65 }
66
run(int argc,char * argv[])67 static int run(int argc, char *argv[]) {
68 int r;
69
70 /* This is mostly intended to be used for scripts which want
71 * to detect whether AC power is plugged in or not. */
72
73 log_parse_environment();
74 log_open();
75
76 r = parse_argv(argc, argv);
77 if (r <= 0)
78 return r;
79
80 r = on_ac_power();
81 if (r < 0)
82 return log_error_errno(r, "Failed to read AC status: %m");
83
84 if (arg_verbose)
85 puts(yes_no(r));
86
87 return r == 0;
88 }
89
90 DEFINE_MAIN_FUNCTION_WITH_POSITIVE_FAILURE(run);
91