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