import static java.lang.System.err;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;


public class Sandbox {

	final static String pathLinux = "Tools/Linux/", pathWindows = "Tools/Windows/", pathMacOSX = "Tools/MacOSX/";
	
	
	public static void main(String[] args) {
		
		/*
		try {
			File log = new File("error.log");
			log.createNewFile();
			FileOutputStream os = new FileOutputStream(log);
			PrintStream ps = new PrintStream(os);
			System.setErr(ps);
		} catch (IOException e) {
			System.err.println("Error: Unable to create error log.");
		}
		*/
		
		System.out.println(runipodpatcher());

	}
	
	private static int runipodpatcher() {
		ProcessBuilder ipodpatcher = new ProcessBuilder();
		switch (getHost()) {
			case -1:
				err.println("Error: Unable to patch iPod.");
				return -1;
			case 00:
				err.println("Error: Unable to patch iPod.");
				return -1;
			case 11:
				ipodpatcher.command(pathLinux + "ipodpatcher-32");
				break;
			case 12:
				ipodpatcher.command(pathLinux + "ipodpatcher-64");
				break;
			case 13:
				ipodpatcher.command(pathLinux + "ipodpatcher-ppc");
				break;
			case 21:
				ipodpatcher.command(pathWindows + "ipodpatcher.exe");
				break;
			case 31:
				ipodpatcher.command(pathMacOSX + "ipodpatcher.dmg");
				break;
			default: // Just in case
				err.println("Error: Unable to patch iPod.");
				return -1;
		}
		try {
			ipodpatcher.start();
			return 1;
		} catch (java.io.IOException e) {
			err.println("Error: Unable to run ipodpatcher binary.");
			err.println("Error: Unable to patch iPod.");
			return 0;
		}
		
	}
	
	/**
	 * Get properties of host computer. Used for calling ipodpatcher binary.
	 * @return
	 * 		-1 if unable to determine, <br>
	 *		00 if Unsupported, <br>
	 * 		11 if Linux (32-bit), <br>
	 * 		12 if Linux (64-bit), <br>
	 * 		13 if Linux (PPC), <br>
	 * 		21 if Windows, <br>
	 * 		31 if Mac OSX
	 */
	private static int getHost() {
		
		// Operating System
		String bufferOS = System.getProperty("os.name");
		
		// Undeterminable
		if (bufferOS == null) {
			err.println("Error: Unable to determine host operating system.");
			return -1;
		} else
	
		// Linux
		if (bufferOS.indexOf("Linux")!=-1) {
			// Architechture
			String bufferArch = System.getProperty("os.arch");
			if (bufferArch.indexOf("ppc")!=-1) {
				return 13;
			} else if (bufferArch.indexOf("64")!=-1) {
				return 12;
			} else if (bufferArch.indexOf("86")!=-1) {
				return 11;
			} else {
				return 11; // Hope will work
			}
		} else
			
		// Windows
		if (bufferOS.indexOf("Windows")!=-1) {
			return 21;
		} else
		
		// Mac OS X	
		if (bufferOS.indexOf("Mac OS X")!=-1) {
			return 31;
			
		// Unsupported
		} else {
			err.println("Error: Operating system not supported.");
			return 00;
		}
	}

}
