import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;


/**
 * Updgrade and move jobs.xml for biomaj 1.2
 * 
 * @author rsabas
 *
 */
public class UpdateToBiomaj1_2 {

	
	/**
	 * Args are :
	 * 	- web_app root directory
	 *  - admin login
	 * @param args
	 */
	public static void main(String[] args) {
		if (args.length != 2) {
			System.err.println("Missing arg : UpdateToBiomaj1_2 <webapp_dir> <admin_login>");
			System.exit(1);
		}
		
		String root = args[0];
		String login = args[1];
		
		if (!new File("/etc/biomaj-watcher/jobs.xml").exists()) { // File not migrated
			
			if (!new File(root +"/jobs.xml").exists() || !new File(root + "/jobs.xsd").exists()) {
				System.err.println("'" + root + "/jobs.xml' or '" + root + "/jobs.xsd missing'");
				System.exit(2);
			}
		
			try {
				// Read jobs.xml content
				BufferedReader br = new BufferedReader(new FileReader(root + "/jobs.xml"));
				String line = null;
				boolean updated = false; // is file already updated ?
				StringBuilder content = new StringBuilder();
				while ((line = br.readLine()) != null) {
					if (line.contains("<user login=")) {
						updated = true;
						break; // File already updated
					}
					content.append(line + "\n");
				}
				br.close();
				
				if (content.indexOf("<job name=") >= 0 && !updated) { // not empty and not updated
					
					// Insert user
					content.insert(content.indexOf("<job name="), "<user login=\"" + login + "\">\n");
					content.insert(content.lastIndexOf("</job>") + 6, "\n</user>");
				}
				
				// Write new jobs.xml in new location
				PrintWriter pw = new PrintWriter("/etc/biomaj-watcher/jobs.xml");
				pw.println(content.toString());
				pw.close();
				
				// Delete old jobs.xml
				if (!new File(root + "/jobs.xml").delete()) {
					System.err.println("Could not delete " + root + "/jobs.xml");
				}
				
				// Move jobs.xsd
				if (!new File(root + "/jobs.xsd").renameTo(new File("/etc/biomaj-watcher/jobs.xsd"))) {
					System.err.println("Could not move " + root + "/jobs.xsd to /etc/biomaj-watcher/jobs.xsd");
					System.exit(3);
				}
				
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		} else {
			System.out.println("jobs.xml already migrated.");
		}
		
	}
}
