60 lines
2.1 KiB
C
60 lines
2.1 KiB
C
#ifndef APP_PATHS_H
|
|
#define APP_PATHS_H
|
|
|
|
/* Direct/local builds stay portable; distribution builds use XDG storage. */
|
|
#ifndef APP_PORTABLE
|
|
#define APP_PORTABLE 1
|
|
#endif
|
|
#ifndef APP_DATA_DIR
|
|
#define APP_DATA_DIR "/usr/share/game-of-life-sandbox"
|
|
#endif
|
|
#ifndef APP_VERSION
|
|
#define APP_VERSION "0.1.0"
|
|
#endif
|
|
|
|
#if !APP_PORTABLE
|
|
static char userBoardsDirectory[PATH_MAX];
|
|
|
|
static bool makeUserDirectory(const char *path) {
|
|
char copy[PATH_MAX];
|
|
if (strlen(path) >= sizeof(copy)) return false;
|
|
snprintf(copy, sizeof(copy), "%s", path);
|
|
for (char *p = copy + 1; ; ++p) {
|
|
if (*p != '/' && *p != '\0') continue;
|
|
char saved = *p;
|
|
*p = '\0';
|
|
if (mkdir(copy, 0700) != 0 && errno != EEXIST) return false;
|
|
struct stat info;
|
|
if (stat(copy, &info) != 0 || !S_ISDIR(info.st_mode)) return false;
|
|
*p = saved;
|
|
if (!saved) break;
|
|
}
|
|
return true;
|
|
}
|
|
|
|
static bool userAppDirectory(char output[PATH_MAX], const char *variable, const char *fallback) {
|
|
const char *base = getenv(variable);
|
|
int count;
|
|
if (base && base[0] == '/') {
|
|
count = snprintf(output, PATH_MAX, "%s/game-of-life-sandbox", base);
|
|
} else {
|
|
const char *home = getenv("HOME");
|
|
if (!home || home[0] != '/') return false;
|
|
count = snprintf(output, PATH_MAX, "%s/%s/game-of-life-sandbox", home, fallback);
|
|
}
|
|
return count >= 0 && count < PATH_MAX && makeUserDirectory(output);
|
|
}
|
|
|
|
static bool initializeUserPaths(char configPath[PATH_MAX]) {
|
|
char configDirectory[PATH_MAX], dataDirectory[PATH_MAX];
|
|
if (!userAppDirectory(configDirectory, "XDG_CONFIG_HOME", ".config")
|
|
|| !userAppDirectory(dataDirectory, "XDG_DATA_HOME", ".local/share")) return false;
|
|
int configLength = snprintf(configPath, PATH_MAX, "%s/settings.cfg", configDirectory);
|
|
int boardLength = snprintf(userBoardsDirectory, PATH_MAX, "%s/boards", dataDirectory);
|
|
return configLength > 0 && configLength < PATH_MAX
|
|
&& boardLength > 0 && boardLength < PATH_MAX
|
|
&& makeUserDirectory(userBoardsDirectory);
|
|
}
|
|
#endif
|
|
#endif
|