]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/ac-power/ac-power.c
coccinelle: make use of SYNTHETIC_ERRNO
[thirdparty/systemd.git] / src / ac-power / ac-power.c
CommitLineData
53e1b683 1/* SPDX-License-Identifier: LGPL-2.1+ */
3d20ed6d 2
ed47df89
LP
3#include <getopt.h>
4
5e332028 5#include "main-func.h"
3d20ed6d 6#include "util.h"
3d20ed6d 7
ed47df89
LP
8static bool arg_verbose = false;
9
10static 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
19static 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("Unhandled option");
57 }
58
baaa35ad
ZJS
59 if (optind < argc)
60 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
61 "%s takes no arguments.",
62 program_invocation_short_name);
ed47df89
LP
63
64 return 1;
65}
66
9a5cedc3 67static int run(int argc, char *argv[]) {
06cdd248
LP
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
ed47df89
LP
73 log_parse_environment();
74 log_open();
75
76 r = parse_argv(argc, argv);
77 if (r <= 0)
9a5cedc3 78 return r;
ed47df89 79
240dbaa4 80 r = on_ac_power();
9a5cedc3
ZJS
81 if (r < 0)
82 return log_error_errno(r, "Failed to read AC status: %m");
06cdd248 83
ed47df89
LP
84 if (arg_verbose)
85 puts(yes_no(r));
86
9a5cedc3 87 return r == 0;
06cdd248 88}
9a5cedc3
ZJS
89
90DEFINE_MAIN_FUNCTION_WITH_POSITIVE_FAILURE(run);