
#include <unistd.h>
#include <stdlib.h>
#include <string.h>

#include "options.h"

char *dir_main_config = NULL,
     *dir_base = NULL;

void dir_cleanup (void) {
	if(dir_base)
		free(dir_base);
	if(dir_main_config)
		free(dir_main_config);
}

void dir_update (void) {
	const char *str = NULL;
	char *home = NULL;
	
	if(dir_main_config)
		free(dir_main_config);
	
	/* build config file name */
	if(!(str = option_get_string("main", "dir.config_file"))) {
		str = "~/.netboard2.rc";
	}
	if (str[0] == '~') {
		home = getenv("HOME");
		dir_main_config = (char *) malloc(strlen(home) + strlen(str));
		strcpy(dir_main_config, home);
		strcat(dir_main_config, str + 1);
	} else {
		dir_main_config = strdup(str);
	}

	/* build base dir name */
	if(!(str = option_get_string("main", "dir.base"))) {
		str = "~/.netboard2/";
	}
	if (str[0] == '~') {
		home = getenv("HOME");
		dir_base = (char *) malloc(strlen(home) + strlen(str));
		strcpy(dir_base, home);
		strcat(dir_base, str + 1);
	} else {
		dir_base = strdup(str);
	}

	/* chdir to base dir */
	if (chdir(dir_base) == -1)
		perror(dir_base);
}

