/*
  File name: main.cpp
  Copyright: (C) 2005 - 2009 Tomasz Kazmierczak
  Copyright: (C) 2006 Kamil Pawlowski
  Copyright: (C) 2009 Tomasz Wisniewski

  Creation date: 27.07.2005
  Last modification date: 17.06.2009

  This file is part of Cytadela

 *   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 3 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.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program. If not, see <http://www.gnu.org/licenses/>.  *

  Application entry point
*/

#include "CCytadelaMain.h"
#include <string>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>
#include <dirent.h>
#include <stdlib.h>

#if defined(__APPLE__)
#include <CoreFoundation/CFURL.h>
#include <CoreFoundation/CFBundle.h>
#endif

#ifndef DATADIR
	#define DATADIR ""
#endif

using namespace std;

bool handleArgs(int argc, char *argv[])
{
	if(argc > 1 and (strcmp(argv[1], "-v") == 0 or strcmp(argv[1], "--version") == 0)) {
		fprintf(stdout, "Cytadela, version 1.0\n");
		return false;
	}
	return true;
}

void changeToDataDirectory()
{
#if defined(__APPLE__)
	CFURLRef resourceURL =  CFBundleCopyResourcesDirectoryURL(CFBundleGetMainBundle());
	char resourcePath[4096];
	CFURLGetFileSystemRepresentation((__CFURL*)resourceURL, TRUE, (UInt8*)resourcePath, 4096);
	chdir(resourcePath);
	CFRelease(resourceURL);
#else
	FILE *file = fopen("obj/PodziemiaT.3dg", "rb");
	if(file != 0)
		fclose(file);
	else chdir(DATADIR);
#endif
}

bool getSysDirectoryPath(string &path)
{
	char *homeDir = getenv("HOME");
	if(homeDir != 0)
		path = string(homeDir) + "/.cytadela";
	else path = "sys";

	//check if the directory exists
	DIR *dir = opendir(path.c_str());
	if(dir == 0) {
		//if it does not exist - create it
		//TODO: replace this mess with a standard C function for creating
		//      directories as soon as such finction is added to the C/C++ language
#if defined(__WIN32__)
		if(-1 == mkdir(path.c_str())) {
			fprintf(stderr, "ERROR: could not create \"%s\" directory\n", path.c_str());
			perror(path.c_str());
			return false;
		}
#else
		if(-1 == mkdir(path.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH)) {
			fprintf(stderr, "ERROR: could not create \"%s\" directory\n", path.c_str());
			perror(path.c_str());
			return false;
		}
#endif
	} else closedir(dir);

	return true;
}

int main(int argc, char *argv[])
{
	fprintf(stdout, "\n");

	//handle the command line arguments
	if(not handleArgs(argc, argv))
		return 0;

	//set current directory to data directory
	changeToDataDirectory();

	CSDLClass *sdl = CSDLClass::instance();
	//first we initialize SDL
	if(not sdl->init()) {
		fprintf(stdout, "Abnormal program termination\n");
		return 1;
	}

	//now we can go into the game
	string path;
	if(not getSysDirectoryPath(path)) {
		fprintf(stdout, "Abnormal program termination\n");
		return 1;
	}
	CCytadelaMain cytadelaMain(path.c_str());
	cytadelaMain.runMain();

	fprintf(stdout, "\n");
	return 0;
}
