]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/machine-id-setup/machine-id-setup-main.c
tree-wide: remove Lennart's copyright lines
[thirdparty/systemd.git] / src / machine-id-setup / machine-id-setup-main.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2
3 #include <errno.h>
4 #include <getopt.h>
5 #include <stdio.h>
6 #include <stdlib.h>
7
8 #include "id128-util.h"
9 #include "log.h"
10 #include "machine-id-setup.h"
11 #include "path-util.h"
12 #include "util.h"
13
14 static char *arg_root = NULL;
15 static bool arg_commit = false;
16 static bool arg_print = false;
17
18 static void help(void) {
19 printf("%s [OPTIONS...]\n\n"
20 "Initialize /etc/machine-id from a random source.\n\n"
21 " -h --help Show this help\n"
22 " --version Show package version\n"
23 " --root=ROOT Filesystem root\n"
24 " --commit Commit transient ID\n"
25 " --print Print used machine ID\n"
26 , program_invocation_short_name);
27 }
28
29 static int parse_argv(int argc, char *argv[]) {
30
31 enum {
32 ARG_VERSION = 0x100,
33 ARG_ROOT,
34 ARG_COMMIT,
35 ARG_PRINT,
36 };
37
38 static const struct option options[] = {
39 { "help", no_argument, NULL, 'h' },
40 { "version", no_argument, NULL, ARG_VERSION },
41 { "root", required_argument, NULL, ARG_ROOT },
42 { "commit", no_argument, NULL, ARG_COMMIT },
43 { "print", no_argument, NULL, ARG_PRINT },
44 {}
45 };
46
47 int c, r;
48
49 assert(argc >= 0);
50 assert(argv);
51
52 while ((c = getopt_long(argc, argv, "hqcv", options, NULL)) >= 0)
53
54 switch (c) {
55
56 case 'h':
57 help();
58 return 0;
59
60 case ARG_VERSION:
61 return version();
62
63 case ARG_ROOT:
64 r = parse_path_argument_and_warn(optarg, true, &arg_root);
65 if (r < 0)
66 return r;
67 break;
68
69 case ARG_COMMIT:
70 arg_commit = true;
71 break;
72
73 case ARG_PRINT:
74 arg_print = true;
75 break;
76
77 case '?':
78 return -EINVAL;
79
80 default:
81 assert_not_reached("Unhandled option");
82 }
83
84 if (optind < argc) {
85 log_error("Extraneous arguments");
86 return -EINVAL;
87 }
88
89 return 1;
90 }
91
92 int main(int argc, char *argv[]) {
93 char buf[SD_ID128_STRING_MAX];
94 sd_id128_t id;
95 int r;
96
97 log_parse_environment();
98 log_open();
99
100 r = parse_argv(argc, argv);
101 if (r <= 0)
102 goto finish;
103
104 if (arg_commit) {
105 const char *etc_machine_id;
106
107 r = machine_id_commit(arg_root);
108 if (r < 0)
109 goto finish;
110
111 etc_machine_id = prefix_roota(arg_root, "/etc/machine-id");
112 r = id128_read(etc_machine_id, ID128_PLAIN, &id);
113 if (r < 0) {
114 log_error_errno(r, "Failed to read machine ID back: %m");
115 goto finish;
116 }
117 } else {
118 r = machine_id_setup(arg_root, SD_ID128_NULL, &id);
119 if (r < 0)
120 goto finish;
121 }
122
123 if (arg_print)
124 puts(sd_id128_to_string(id, buf));
125
126 finish:
127 free(arg_root);
128 return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
129 }