package form.run;

import form.io.*;
import java.lang.*;
import java.io.*;
import java.util.*;

public class CGIReceiver{

public CGIReceiver(){}

	static String name;
	static String email;
	static String id;
	static String userId;
	static String data;

	static String configFile = "npib.config";

	static String local = "local";
	static String remote = "remote";

	static String outRoot = "/www/jwave/output/";
	static String webRoot = "/output/";
	static String commandFile = "npib.commands";
	static String tempname = "npib.in";
	static String sshScriptDir = "./";
	static String host = "pse.sv.vt.edu";
	static String fromEmail = "npib@www.jwave.vt.edu";

	static String OUTROOT = "outroot";
	static String WEBROOT = "webroot";
	static String COMMANDFILE = "commandfile";
	static String TEMPNAME = "tempname";
	static String SSHSCRIPTDIR = "sshscriptdir";
	static String HOST = "hostname";
	static String FROMEMAIL = "email";

	static String COMMENT = "#";

	static private void config(){

        String input = "";
        String line ="";
		StringTokenizer s;

		input = ReadFiles.readFile(configFile);
		s = new StringTokenizer(input);

		while (s.hasMoreTokens()){
			line = s.nextToken();
			if (line.equalsIgnoreCase(OUTROOT)){
				outRoot = s.nextToken();
			}
			else if (line.equalsIgnoreCase(WEBROOT)){
				webRoot = s.nextToken();
			}
			else if (line.equalsIgnoreCase(COMMANDFILE)){
				commandFile = s.nextToken();
			}
			else if (line.equalsIgnoreCase(TEMPNAME)){
				tempname = s.nextToken();
			}
			else if (line.equalsIgnoreCase(SSHSCRIPTDIR)){
				sshScriptDir = s.nextToken();
			}
			else if (line.equalsIgnoreCase(HOST)){
				host = s.nextToken();
			}
			else if (line.equalsIgnoreCase(FROMEMAIL)){
				fromEmail = s.nextToken();
			}
    	}
	}

	public static void main(String[] args){

		config();
		String file = args[0];
		System.out.println("Cache-Control: no-cache");
	    System.out.println("Content-type: text/plain\n\n");
	    file = URLDecoder.decode(file);

		if(file.startsWith("name=")){
			getName(file);
			makeDir(id);
		}
		else if(file.startsWith("close")){
			file=file.substring(5);
			getId(file);
			new WriteFiles(outRoot+id+"/"+tempname,outRoot+id);
			email=data.substring(1,data.indexOf("&",2));
			System.out.println("TO "+email);
			data=data.substring(1+data.indexOf("&",2));
			System.out.println("DATA recvd: "+data);
			execute();
			
		}
		else if(file.startsWith("id=")){
			getId(file);
			writeData();
		}

		System.out.println("id="+id);
		System.out.println("url="+webRoot+id);

	}

	static private void execute(){
		String name = id.substring(id.indexOf("/")+1);
		name = name.substring(0,name.indexOf("/"));

		String fileLocs = ReadFiles.readFile(commandFile);

		String fileName = fileLocs.substring(1+fileLocs.indexOf(userId)+userId.length(),fileLocs.indexOf("\n",fileLocs.indexOf(userId)));

		String file = ReadFiles.readFile(fileName);

		String script = file.substring(1+file.indexOf(name)+name.length(),file.indexOf("\n",1+file.indexOf(name)+name.length()));

		System.out.println("Script name:"+file+" Name:"+name);
		StringTokenizer s = new StringTokenizer(script);

		String type = s.nextToken();

		script = s.nextToken();

		RunProg rp = new RunProg(outRoot+id);

		if (type.equalsIgnoreCase(local) ){
			rp.local(script);
		}
		else if (type.equalsIgnoreCase(remote) ){
				rp.remote(sshScriptDir,script,data);
		}
		new ReceiverMailer(outRoot+id+"/", "http://"+host+webRoot+id, email,fromEmail,host);
	}

	static private void getId(String file){
		//StringTokenizer s = new StringTokenizer(file,"=&");
		//throw out "id"
		int start = file.indexOf("=");
		int middle = file.indexOf("/");
		int end = file.indexOf("&");
		userId = file.substring(start+1,middle);
		id = file.substring(start+1,end);
		file = file.substring(end+1);

		start = file.indexOf("=");
		String type = file.substring(0,start);
		data = file.substring(start+1);
	}

	static void writeData(){
		try{
			FileWriter f = new FileWriter(outRoot+id+"/"+tempname,true);
			f.write(data,0,data.length());
			f.close();
		}catch(Exception e){}
	}

	static void getName(String file){
		StringTokenizer s = new StringTokenizer(file,"=&");
		//throw out "name"
		s.nextToken();
		name = s.nextToken();
		s.nextToken();
		email = s.nextToken();

		id = makeId(name,email);
	}

	static void makeDir(String id){

		try {
		Process p = Runtime.getRuntime().exec("mkdir "+outRoot+id);
		p.waitFor();
		}catch  (java.io.IOException e){System.out.println("Can't create dir "+outRoot+id);}
		catch(java.lang.InterruptedException e){System.out.println("encountered error while creating dir "+outRoot+id);}
	
	}

	static String makeId(String name, String email){
		String time = getTime();	
		String id;
		String newid;
		id = name+"/"+email+time;
		int l = id.indexOf("@");
		newid = id.substring(0,l);
		newid +="_";
		newid +=id.substring(l+1);
		return newid;
	}

	static public String getTime(){
		Calendar calendar = new GregorianCalendar();

		String time = (calendar.get(Calendar.MONTH)+1)+"";
		time += "-"+calendar.get(Calendar.DAY_OF_MONTH);
		time += "-"+calendar.get(Calendar.YEAR);
		time += "-"+calendar.get(Calendar.HOUR_OF_DAY)+":";

		if (calendar.get(Calendar.MINUTE) < 10) time +="0";
			time += calendar.get(Calendar.MINUTE)+":";

		if (calendar.get(Calendar.MINUTE) < 10) time +="0";
			time += calendar.get(Calendar.SECOND);

		time += ":"+calendar.get(Calendar.MILLISECOND);

		return time;
	}

}
