/*
 * dirs.c
 * 
 * Copyright (C) 2005-2007  Josef Kufner <jk@myserver.cz>
 * 
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 */

#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);
}

