#include <iostream>
#include <fstream>
#include <iomanip>
#include <string.h>
#include <cstdlib>
#include <sstream>
using namespace std;
 
#ifndef CDROM
#include "wrapper.h"
#include "libsearch4j.h"
bool extract_bundled_file( const char[], int, char*, bool );
#else
bool prep_java( string wd );
#endif

void usage( char* progname, int exitvalue = -1 ) {
	cerr
		<< "Usage: " << progname << " [OPTIONS]" << endl
		<< "OPTIONS: " << endl
		<< " -h, -help	 Display this usage message" << endl
		<< " -textonly   Do a non-graphical command line installation" << endl
		<< " -extract    Extract the jar file, this can " << endl;
	#ifdef CDROM
	cerr << " -wd PATH			Look for the CD-ROM at PATH" << endl;
	#endif

	exit( exitvalue );
}

int main(int argc, char** argv) {

	char wdc[1024];
	getcwd(wdc, sizeof(wdc));
	string wd = "";
	wd.append( wdc );
	
	string scratch = (getenv("TMPDIR") == NULL) ? "/tmp" : getenv("TMPDIR");
	string tempdir = scratch + "/greenstone-installer.tmp"; //temporary directory where we will store extracted files
	bool succeeded = false;
	bool text_mode = false;

	//parse arguments
	string a;
	for ( int i=1; i<argc; i++ ) {
		a = argv[i];
		if ( a.compare("-wd") == 0 ) {
			wd = "";
			wd.append( argv[++i] );
		} else if ( a.compare("-h") == 0 || a.compare("-help") == 0 || a.compare("--help") == 0) {
			usage( argv[0], 0 );
		} else if ( a.compare("-textonly") == 0 || a.compare("-text") == 0 || a.compare("text") == 0 ) {
			//cerr << "-text is deprecated, please use -extract and then run \"java -jar greenstone.jar text\"" << endl;
			text_mode = true;
#ifndef CDROM
		} else if ( a.compare("-extract") == 0 || a.compare("--extract") || a.compare("-x")) {
			cout << "----------------------------" << endl;
			cout << "Extracting java installer..." << endl;
			cout << "----------------------------" << endl;
			bool result = extract_bundled_file( greenstonejar, sizeof(greenstonejar), "greenstone.jar", false);
			if(result){
				cout << "\nExtraction Complete" << endl;
				cout << "You can now run \"java -jar greenstone.jar text\" to run the installer from the command line\n" << endl;
				return 0;
			}
			else{
				cerr << "\nThere was an error while extracting the java installer" << endl;
				return 1;
			}
#endif
		} else {
			cerr << "Unrecognised option '" << a << "'" << endl;
			usage(argv[0]);
		}
	}

	#ifdef CDROM
	//ensure working directory is correct
	FILE* pFile;
	pFile = fopen( (wd+"/Software/core/all/uninst.jar").c_str(), "r");
	if ( pFile == NULL ) {
		cerr << "Could not find cdrom at '" << wd << "'." << endl;
		cerr << "Please enter the path the CDROM [/media/cdrom]: ";
		getline(cin, wd);
		if ( wd.compare("") == 0 ) {
			wd = "/media/cdrom";
		}
	} else {
		fclose(pFile);
	}

	pFile = fopen( (wd+"/Software/core/all/uninst.jar").c_str(), "r");
	if ( pFile == NULL ) {
		cerr << "Could not find cdrom at '"<< wd << "'." << endl;
		cerr << "Please run the installer again" << endl;
		exit(-1);
	} else {
		fclose(pFile);
	}
	#endif

	//create the temp folder
	cout << "Creating temp directory..." << endl;
	succeeded = ( 0 == system( ("mkdir " + tempdir).c_str() ) );
	if ( !succeeded ) {
		cerr << "Failed to create the temp directory '" << tempdir << "'. " <<
		 "Check that it does not already exist. Also check that you have write " <<
		 "permissions to '" << scratch << "', or set the environment variable TMPDIR to " <<
		 "a directory where you do have write permissions." << endl <<
		"Exiting" << endl;
		return 1;
	}
	
	#ifndef CDROM

	string jarfile = tempdir + "/greenstone.jar"; //where we will store the jar file
	string javafile = tempdir + "/@java.installer@"; //where we will store the java tar file


	//extract files
	cout << "Extracting installer jar..." << endl;
	succeeded = extract_bundled_file( greenstonejar, sizeof(greenstonejar), (char*)jarfile.c_str(), false);

	#ifdef java_is_bundled
	cout << "Preparing Greenstone installer..." << endl;
	succeeded = extract_bundled_file( java, sizeof(java), (char*)javafile.c_str(), true ) && succeeded;
	#endif
		
	if ( !succeeded ) {
		cerr << "Failed to extract one or more resources" << endl;
		cerr << "This installer may not have sufficient file permissions to write it to disk" << endl;
		cerr << "Or, the files may be corrupt or missing from this executable" << endl;
		cerr << "Exiting" << endl;
		return 1;
	}

	#endif

	//change to the temp directory
	chdir( tempdir.c_str() );


	#ifndef CDROM
	#ifdef java_is_bundled
	succeeded = (system( "/bin/sh -c ./@java.installer@ > /dev/null" ) == 0);
	succeeded = succeeded && ( system( "tar -xf jre.tar" ) == 0 );
	if ( !succeeded ) {
		cout << "Failed to extract the bundled java archive to the temp directory" << endl;
		cout << "You need the tar program on your PATH" << endl;
		cout << "Exiting" << endl;
		return 1;
	}
	#endif

	//check if an appropriate java is found
	Jvm minimum; minimum.setVersionFromString( "@java.min.version@" );
	string phint = "./@java.extracted@";
	string hint = "";
	Jvm foundJvm;
	bool jvmFound = find( foundJvm, true, minimum, false, false, phint, hint, false );

	//if the jvm was not found, report not found
	if ( !jvmFound ) {

		//did not find a good java
		cout << "Greenstone requires java @java.min.version@ or greater." << endl;
		
		//tell them if java is absent or just too old
		Jvm tmpJvm;
		if ( find( tmpJvm, false, minimum, false, false, phint, hint, false ) ) {
			cout << "You have java, but it is too old." << endl;
		} else {
			cout << "Could not find java on your system." << endl;
		}
		
		cout << "Install java (@java.min.version@ or greater) and set JAVA_HOME or JRE_HOME, and try again" << endl;
		#ifndef java_is_bundled
		cout << "Or, download a greentsone3 installer with bundled java and use that instead of this one" << endl;
		#endif

	//if we have found it, launch the installer
	} else {

		cout << "Launching Installer ..." << endl;
		int launch_exit_code = 0;
		launch_exit_code = system( (foundJvm.getExecutable() + " -Xmx300M -jar greenstone.jar" + (text_mode?" text":"") ).c_str() );

		//report how it went
		if ( launch_exit_code == 0 ) {
			cout << "Setup complete" << endl;
		} else {
			cout << "The installer exited with an error" << endl;
			cout << "Greenstone may not be correctly installed" << endl;
		}

	}
	#else
		bool java_ready = prep_java( wd );
		if ( java_ready ) {
			string cmd = "./jre/bin/java -Dorig.dir=\"" + wd + "\" -jar " + wd + "/Java/Jars/linux.jar" + (text_mode?" text":"");
			system( cmd.c_str() );
		}
	#endif

	//change to the scratch dir for the following operation
	chdir(scratch.c_str());

	//delete the temp files
	cout << "Deleting the temp directory" << endl;
	system( ("rm -rf " + tempdir).c_str() );

	return 0;

}
#ifndef CDROM
bool extract_bundled_file( const char data[], int size, char* filename, bool make_executable) {

	if ( size == 0 ) return false;

	//delete the file if it exists
	remove( filename );

	//open the file
	fstream binary_file( filename, ios::out|ios::binary );
	if ( !binary_file.good() ) {
		binary_file.close();
		return false;
	}

	//write the file
	binary_file.write( data, size );
	if ( !binary_file.good() ) {
		binary_file.close();
		return false;
	}

	//close the file
	binary_file.close();
	if ( !binary_file.good() ) {
		binary_file.close();
		return false;
	}

	if ( make_executable ) {
		string command = "chmod a+x " + string(filename);
		system( command.c_str() );
	}

	return true;

}
#else

bool prep_java( string wd ) {


  string jTestCmd = "./jre/bin/java -version >/dev/null 2>&1";

  //try to extract straight off cd
  string j1cmd = wd + "/Java/Linux/jre_bin && tar -xf jre.tar && " + jTestCmd;
  int j1status = system(j1cmd.c_str());
  system("/bin/rm -f jre.tar");
  
  if (WEXITSTATUS(j1status)!=0) {
    cerr << "Unable to extract java straight off CD-ROM." << endl;
    cerr << "This is probably because your CD-ROM was mounted with 'noexec'." << endl;
    cerr << "It can be changed by a system administrator" << endl << endl;
    cerr << "Copying Java to local disk so it can be run" << endl;
    
    string cdtar_home = wd + "/Java/Linux/";
    string tcmd = "(cd \"" + cdtar_home + "\" ; tar cf - jre_bin )";
    tcmd += "| tar xvf - ";
    //tcmd += "| awk 'BEGIN{C=0}{C++; printf(\".\"); if (C%70==0) printf(\"\\n\");}END{printf(\"\\n\")}'";

    int tstatus = system(tcmd.c_str());
    
    if (WEXITSTATUS(tstatus)!=0) {
      cerr << "Failed to copy Java to disk" << endl;
      cerr << "Please make sure you have write permissions in the directory where you run the installer" << endl;
    }
    else {

      string j2cmd = "./jre_bin && tar -xf jre.tar && " + jTestCmd;
      int j2status = system(j2cmd.c_str());
      system("/bin/rm -f jre.tar jre_bin");

      if (WEXITSTATUS(j2status)!=0) {
        cerr << "Unable to run copied Java" << endl;
        return false;
      }
    }
  }

  // to get to here, full_java must be set (and working)

  return true;
}

#endif