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

  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>
#include <errno.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.1.0\n");
		return false;
	}
	return true;
}

bool changeToDataDirectory()
{
	int result = 0;
	char dataDir[FILENAME_MAX] = {0};
#if defined(__APPLE__)
	CFURLRef resourceURL =  CFBundleCopyResourcesDirectoryURL(CFBundleGetMainBundle());
	CFURLGetFileSystemRepresentation((__CFURL*)resourceURL, TRUE, (UInt8*)dataDir, FILENAME_MAX);
	result = chdir(dataDir);
	CFRelease(resourceURL);
#else
	FILE *file = fopen("obj/PodziemiaT.3dg", "rb");
	if(file != 0)
		fclose(file);
	else {
		snprintf(dataDir, FILENAME_MAX, "%s", DATADIR);
		result = chdir(dataDir);
	}
#endif
	if(result != 0) {
		fprintf(stderr, "ERROR: could not open the data directory \"%s\": %s\n", dataDir, strerror(errno));
		return false;
	}
	return true;
}

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: %s\n", path.c_str(), strerror(errno));
			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: %s\n", path.c_str(), strerror(errno));
			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
	if(not changeToDataDirectory()) {
		fprintf(stdout, "Abnormal program termination\n");
		return 1;
	}

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