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