finish migrating old code to work with gdbus-codegen types, cleaned up config IO...
[systembsd.git] / src / config.c
1 #include <unistd.h>
2 #include <fcntl.h>
3 #include <gio/gio.h>
4
5 static GKeyFile *config;
6
7 static const gchar *CONFIG_KEYS[] = {
8 "PrettyHostname",
9 "IconName",
10 "ChassisType"
11 };
12
13 /* NULL if key doesn't exist */
14 gchar *get_option(gchar *key, gchar *group) {
15
16 if(!group)
17 group = "default";
18
19 return g_key_file_get_string(config, group, key, NULL);
20 }
21
22 /* false if key isn't already defined or value is invalid */
23 gboolean set_option(gchar *key, gchar *value, gchar *group) {
24
25 if(!group)
26 group = "default";
27
28 if(!g_key_file_get_string(config, group, key, NULL))
29 return FALSE;
30
31 //TODO safteycheck value
32 g_key_file_set_string(config, group, key, value);
33 return TRUE;
34 }
35
36 /* initial load/check */
37 gboolean config_init() {
38
39 if(config)
40 return TRUE; //already init'd
41
42 config = g_key_file_new();
43
44 const gchar *config_path;
45 GStatBuf *config_lstat;
46
47 config_path = "/etc/systemd_compat.conf";
48
49 /* does conf exist? */
50 if(g_lstat(config_path, config_lstat)) {
51
52 /* if not, can we write it */
53 if(g_access("/etc/", W_OK)) {
54 g_printf("%s\n", "no write permissions for /etc/! exiting..");
55 return FALSE;
56 }
57
58 int config_descr;
59 config_descr = g_open(config_path, O_CREAT, 644);
60
61 gchar *posix_hostname;
62 posix_hostname = g_malloc(255);
63
64 gethostname(posix_hostname, 255);
65
66 g_key_file_set_string(config, "hostnamed", "Hostname", posix_hostname);
67 g_key_file_set_string(config, "hostnamed", "PrettyHostname", "");
68 g_key_file_set_string(config, "hostnamed", "IconName", "Computer");
69 g_key_file_set_string(config, "hostnamed", "ChassisType", "laptop"); //TODO set these correctly
70
71 if(!g_key_file_save_to_file(config, config_path, NULL)) {
72 g_printf("failed to write config to %s!\n", config_path);
73 g_free(posix_hostname);
74 return FALSE;
75 }
76
77 g_printf("wrote config to %s\n", config_path);
78
79 g_free(posix_hostname);
80
81 return TRUE;
82
83 /* it does exist, read it */
84 } else {
85
86 if(!g_access(config_path, W_OK)) {
87 g_printf("%s\n", "no write permissions for /etc/! exiting..");
88 return FALSE;
89 } else if(g_key_file_load_from_file(config, config_path, G_KEY_FILE_KEEP_COMMENTS, NULL))
90 return TRUE;
91
92 g_printf("could not read config at %s! exiting..", config_path);
93 return FALSE;
94 }
95 }