#include "acidlaunch.h"

#include <fstream>
#include <strstream>
#include <sys/stat.h>
#include <unistd.h>

using std::strstream;

char* prefsFileName(const char* name)
{
	char* homedir = getenv("HOME");
	char* rcfile;

	rcfile = new char[strlen(homedir) + strlen("/.acidlaunch/") + strlen(name) + 1];
	sprintf(rcfile, "%s/.acidlaunch/%s", homedir, name);
	//printf("%s\n", rcfile);
	return rcfile;
}

AcidLaunchNode* readConfig(const string& name)
{
	xmlDocPtr tree;
	xmlNodePtr root;
	AcidLaunchNode* config = NULL;
	char* filename = 	prefsFileName(name.c_str());
	
	if(tree = xmlParseFile(filename))
	{
		if(root = xmlDocGetRootElement(tree))
		{
			if(!xmlStrcmp(root->name, (const xmlChar*)"acidlaunchconfig"))
			{
				config = new AcidLaunchNode(root);
				config->parseNodes(root);
			}
		}
		xmlFreeDoc(tree);
	} else {
		cerr << "Error reading prefs file!\n";
		exit(10);
	}

	delete[] filename;

	return config;
}

/* check if ~/.acidlaunch exists, and if it doesn't, copy the default prefs
	dir over */

static const char* prefsfilenames[] = {"config.xml", "default.png"};
static const int numprefsfilenames = 2;

#define SHAREDIR PREFIX "/share/acidlaunch/"

bool createInitialConfig()
{
	string prefsdir;
	struct stat filestat;

	prefsdir = getenv("HOME");
	prefsdir+="/.acidlaunch";

	//cout << PREFIX << endl << SHAREDIR << endl;
	
	/* check if dir exists - create it if it doesn't */
	if(stat(prefsdir.c_str(), &filestat))
	{
		if(mkdir(prefsdir.c_str(), 0700))
		{
			cerr << "failed to create directory\n";
			return false;
		}
	}

	/* check prefs files - copy over if they doesn't exist */
	for(int i=0; i < numprefsfilenames; i++)
	{
		/* work out the filename */
		char* prefsfile = prefsFileName(prefsfilenames[i]);
			
		/* check if it exists */
		if(stat(prefsfile, &filestat))
		{
			/* it doesn't - copy it over */
			string command;

			command = "cp ";
			command+= SHAREDIR;
			command+= prefsfilenames[i];
			command+= " ";
			command+= prefsfile;
			//cerr << command << endl;
			system(command.c_str());
		}
	}
	return true;
}


syntax highlighted by Code2HTML, v. 0.9.1