/*
 * 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 <glib.h>
#include <unistd.h>
#include <stdlib.h>
#include <assert.h>
#include <string.h>

#include "dirs.h"
#include "options.h"

char *dir_main_config = NULL,
     *dir_base = NULL;

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

void dir_update (void) {
	const char *str = NULL;
	
	if(dir_main_config)
		g_free(dir_main_config);
	
	if(dir_base)
		g_free(dir_base);
	
	/* build config file name */
	if(!(str = option_get_string("main", "dir", "config_file"))) {
		str = "~/.netboard2.rc";
	}
	dir_main_config = dir_build_filename(str, NULL);

	/* build base dir name */
	if(!(str = option_get_string("main", "dir", "base"))) {
		str = "~/.netboard2/";
	}
	dir_base = dir_build_filename(str, NULL);

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

/* Returns fully expanded filename.
 * Free result with g_free().
 * '~' is expanded in dir only.
 * file can be NULL, then dir only will be used .
 */
char *dir_build_filename(const char *dir, const char *file)
{
	assert(dir != NULL);

	char *slash = file && file[0] && dir[0] && dir[strlen(dir) - 1] != '/' ? "/" : "";

	if (dir[0] == '~' && (dir[1] == '\0' || dir[1] == '/'))
		return g_strjoin(NULL, getenv("HOME"), dir + 1, slash, file, NULL);
	else
		return g_strjoin(NULL, dir, slash, file, NULL);
}

