#!/usr/bin/php
<?php
	/**
	*	~=< WELCOME TO FFLAG >=~
	*	Dependencies:
	*	  php5-cli (PHP 5.x commandline interpreter)
	*	  php5-curl (CURL module for PHP 5.x)
	*	  php5-tidy (HTML cleaner)
	*
	*   html2lrf (from Calibre) - for BBeB output only
	*
	*   Written by: erayd
	*   Windows version written by: rgibbo
	*/

	//Setup environment
	if (!function_exists('posix_getcwd')) {

		//Windows version since there is no posix functions
		define('CALLDIR', getcwd());
		define('PID', getmypid());

		//Temp folder, this is unique to the user
		define('TEMP', getenv('TEMP'));
	
	}
	else {

		//Linux version
		define('CALLDIR', posix_getcwd());
		define('PID', posix_getpid());

		//Temp folder, this is the global temp folder
		define('TEMP', '/tmp');

	}

	//Change to current dir
	chdir(dirname(__FILE__));

	//Get the error console reference
	$errfile = fopen('php://stderr', 'w');

	//Config
	require_once('inc/args.inc.php');
	$config = getCliArgs();

	//Main includes
	require_once('inc/misc.inc.php');
	require_once("source/{$config['source']}.source.php");
	require_once('codec/html.codec.php');
	require_once("codec/{$config['format']}.codec.php");

	//Various function names
	$check_deps_func = "check_deps_{$config['format']}";
	$get_story_func = "{$config['source']}_get_story";
	$convert_func = "convert_story_{$config['format']}";

	//Check Dependencies
	check_deps_html();
	$check_deps_func();

	//Main Application Logic
	$story = $get_story_func($config['storyid']);
	printMsg("\t* Compling {$config['format']} data...\n");
	$output = $convert_func($story);

	//Output the compiled file
	//if (isset($config['outfile'])) { //Removed since no need to print to the console on windows (don't know about linux though)

	//Output the compiled file if it the story is valid
	if ($story['meta']['title'] != "") {

		//Change to the directory that called this
		chdir(CALLDIR);

		//Create the file name
		if (!isset($config['outfile']) || $config['outfile'] == '-') $config['outfile'] = getBaseFilename($story) . ".{$config['format']}";
		
		//Output the file
		printMsg("\t* Writing output to {$config['outfile']}...\n");
		file_put_contents($config['outfile'], $output);
/*	}
	else {

		//Output to the console
		$fh = fopen('php://stdout', 'w');
		fwrite($fh, $output);
		fclose($fh);*/
	}

	//Cleanup
	fclose($errfile);
?>
