From dd6321c0acf7b0570811200a205cc4104bee49c7 Mon Sep 17 00:00:00 2001 From: David Härdeman Date: Thu, 9 Jul 2020 20:36:15 +0200 Subject: Implement a basic init command in minecctl to create an initial example config --- minecctl/misc.c | 73 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 73 insertions(+) (limited to 'minecctl/misc.c') 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 #include #include +#include +#include +#include +#include +#include #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() { -- cgit v1.2.3