diff options
author | David Härdeman <david@hardeman.nu> | 2020-07-09 20:36:15 +0200 |
---|---|---|
committer | David Härdeman <david@hardeman.nu> | 2020-07-09 20:36:15 +0200 |
commit | dd6321c0acf7b0570811200a205cc4104bee49c7 (patch) | |
tree | 52da75427a0c1d237806fbebba23025afd79d28d /minecctl/misc.c | |
parent | 4ae60696aed938347cc1cf2a5d8f5a2b86292132 (diff) |
Implement a basic init command in minecctl to create an initial example config
Diffstat (limited to 'minecctl/misc.c')
-rw-r--r-- | minecctl/misc.c | 73 |
1 files changed, 73 insertions, 0 deletions
diff --git a/minecctl/misc.c b/minecctl/misc.c index 525b09a..26cbc86 100644 --- a/minecctl/misc.c +++ b/minecctl/misc.c @@ -5,11 +5,84 @@ #include <stdarg.h> #include <string.h> #include <termios.h> +#include <sys/types.h> +#include <sys/stat.h> +#include <fcntl.h> +#include <pwd.h> +#include <errno.h> #include "shared/utils.h" #include "misc.h" #include "minecctl.h" +static const char *get_homedir() +{ + const char *e; + struct passwd *passwd; + uid_t uid; + + e = getenv("HOME"); + if (e && e[0] == '/') + return e; + + uid = getuid(); + if (uid == 0) + return "/root"; + + passwd = getpwuid(uid); + if (passwd && passwd->pw_dir[0] == '/') + return passwd->pw_dir; + + return NULL; +} + +int open_subdir(int dfd, const char *subdir, bool nofail) +{ + int sfd; + + if (nofail && mkdirat(dfd, subdir, 0777) < 0 && errno != EEXIST) { + error("Unable to create subdirectory %s: %m", subdir); + return -1; + } + + sfd = openat(dfd, subdir, O_PATH | O_CLOEXEC | O_DIRECTORY); + if (sfd < 0 && nofail) + error("Unable to open subdirectory %s: %m", subdir); + + return sfd; +} + +int open_xdg_dir(const char *envname, const char *altpath, bool nofail) +{ + const char *e; + const char *h; + int dfd, hfd; + + e = getenv(envname); + if (e && e[0] == '/') { + dfd = open(e, O_PATH | O_CLOEXEC | O_DIRECTORY); + if (dfd < 0) + error("Unable to open $%s(%s): %m", envname, e); + return dfd; + } + + h = get_homedir(); + if (!h) { + error("Unable to determine home directory"); + return -1; + } + + hfd = open(h, O_PATH | O_CLOEXEC | O_DIRECTORY); + if (hfd < 0) { + error("Unable to open $HOME(%s): %m", h); + return -1; + } + + dfd = open_subdir(hfd, altpath, nofail); + close(hfd); + return dfd; +} + /* FIXME: Can be shared */ void set_use_colors() { |