import arsd.cgi;
//import arsd.sqlite;
import std.file;
import std.conv;
import std.process;

string host_port = ":9000";
string allowed_host = "";


	string fileToString(string path){
		auto file = File(path, "r");
		string contents = "";
		while (!file.eof()) {
			contents ~= file.readln();
		}
		file.close();
		return contents;
	}
	string get_header(){
		return fileToString("public/header.html");
	}
	string get_footer(){
		return fileToString("public/footer.html");
	}
	bool run_script(string script_path){
        try{
            string script_command = "chmod +x " ~ script_path ~ " && bash -c "~ script_path;
            writeln("calling::: " ~ script_command);
            auto cont = executeShell(script_command);
            if(cont.status != 0) {
                writeln("failed to run script command");
                //return "Failed";
                return false;
            } else {
                writeln("script output " ~ cont.output);
                return true;
            }
		} catch (Exception e) {
			return false;
		}
	}
	void handler(Cgi cgi) {
        try{
            string host = cgi.host.replace(host_port, "");
            string path = cgi.pathInfo;
            if(path == "/favicon.ico"){
                return;
            }
            if(cgi.remoteAddress ~= allowed_host.split(":"[0])){ // ignore the port.
                cgi.write("<html> Connections are not allowed from: " ~ cgi.remoteAddress ~ "</html>");
                return;
            }
            writeln("Trying to access: " ~host ~path);
            string script_path = getcwd() ~"/" ~ host ~ "/" ~ "run.sh";
            writeln("script_path: " ~ script_path);
            if(script_path.exists){
                writeln("script_path exists: Trying to access: " ~host);
                //Not needed currently. auto fail_script = fileToString(script_path);
                writeln("Running script: \r\n" ~ script_path);
                auto result = run_script(script_path);
                if(result){
                    cgi.write("<html> successfully ran script.</html>");
                } else {
                    cgi.write("<html> Failed to run script.</html>");
                }
                writeln("done with script");
            } else {
                writeln("site path doesn't exist.");
                cgi.write("<html> Hello " ~ cgi.remoteAddress ~ " The host: " ~ host ~ " is not configured.</html>");
            }
        } catch (Exception e){
            writeln("ʕノ•ᴥ•ʔノ ︵ ┻━┻ Exception thrown:  "~ e.toString());
            //throw o;
            cgi.setResponseStatus("500 Internal Server Error");
            cgi.write("ʕノ•ᴥ•ʔノ ︵ ┻━┻ 500 Internal Server Error.", true);
        }
    }

	//mixin GenericMain!handler;

void main(string[] args) {
    //TODO: Fix this to load the acceptable host from an argument, or config file.
    allowed_host = "127.0.0.1";

    //TODO: Figure out a better way of setting defaults, this is pretty dumb.
    string[] newargs;
    writeln(to!string(args));
    args = [];
    writeln(to!string(args));
    newargs ~= "./main";
    newargs ~= "--listen";
    newargs ~= "http://localhost" ~ host_port;
    args = newargs;
    writeln(to!string(args));
    // this is all the content of [cgiMainImpl] which you can also call

    // cgi.d embeds a few add on functions like real time event forwarders
    // and session servers it can run in other processes. this spawns them, if needed.
    if(tryAddonServers(args))
        return;

    // cgi.d allows you to easily simulate http requests from the command line,
    // without actually starting a server. this function will do that.
    if(trySimulatedRequest!(handler, Cgi)(args))
        return;

    RequestServer server;
    // you can change the default port here if you like
    // server.listeningPort = 9000;

    // then call this to let the command line args override your default
    server.configureFromCommandLine(args);

    // here is where you could print out the listeningPort to the user if you wanted

    // and serve the request(s) according to the compile configuration
    server.serve!(handler)();

    // or you could explicitly choose a serve mode like this:
    // server.serveEmbeddedHttp!requestHandler();
}
