// var.trim用
javascript:String.prototype.trim = function(){ return this.replace(/(^\s+|\s+$)/g,'') }; 

// 結果出力ファイル名
var GET_VERSION_FILENAME = "Get_version.xml";
var UPDATE_NORMAL_FILENAME = "Update_normal.xml";
var UPDATE_FORCE_FILENAME = "Update_force.xml";
var INSTALL_FILENAME = "Install.xml";
var UNINSTALL_FILENAME = "Un_install.xml";

// 各コマンド引数
var GET_VERSION_ARG = "version";
var UPDATE_NORMAL_ARG = "UpdateNormal";
var UPDATE_FORCE_ARG = "UpdateForce";
var INSTALL_ARG = "Install";
var UNINSTALL_ARG = "Uninstall";

// Version表示時のRevision
var REVISION = "Rev ";

// "WScritp.Shell"を確保
	var objShell = WScript.CreateObject("WScript.Shell");

//----------------------------------------------------------
// OSのアーキテクチャがx86であるかどうか
function isOSArchitectureX86() {
	try {
		if(GetObject("winmgmts:win32_OperatingSystem=@").OSArchitecture.indexOf("32") != -1) {
			return true;
		}
		return false;
	} catch (e) {
		// WindowsXP(x86)とWindows2003(x86)はこのパターン
		return true;
	}
}
//----------------------------------------------------------
// 指定のフォルダが存在するかどうか
function isDirExist(dirPath) {
	var objFSO = WScript.CreateObject("Scripting.FileSystemObject");
	return objFSO.FolderExists(dirPath);
}

//----------------------------------------------------------
// URUアンインストーラ格納場所
function uruUninstallerPath() {
	var srturuUninstallPath;
	var objShell = WScript.CreateObject("WScript.Shell");

	if(isOSArchitectureX86()) {
		srturuUninstallPath = objShell.RegRead("HKLM\\SOFTWARE\\Microsoft\\Windows\\" +
			"CurrentVersion\\Uninstall\\{5E8B5993-DF48-4B3C-9314-79CE1BFB9D73}\\UninstallString");
	} else {
		srturuUninstallPath = objShell.RegRead("HKLM\\SOFTWARE\\Wow6432Node\\Microsoft\\Windows\\" +
			"CurrentVersion\\Uninstall\\{5E8B5993-DF48-4B3C-9314-79CE1BFB9D73}\\UninstallString");
	}

	// "setup.exe"以下を削除
	return srturuUninstallPath.substr(0, srturuUninstallPath.indexOf("setup.exe"));
}

//----------------------------------------------------------
// URU Current Version取得
function getCurrentURUVersion() {
	try {
        // レジストリからURUのインストールフォルダを取得
        var reg_key = "HKLM\\SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment\\URAIDUTLPATH";
		var objFSO = WScript.CreateObject("Scripting.FileSystemObject");
		var objInput = objFSO.OpenTextFile(objShell.RegRead(reg_key) + 
			"\\server\\version.txt", 1, false); // readOnlyでOpen
		var strLineVer = objInput.ReadLine();
		var strLineRev = objInput.ReadLine();
		objInput.close();

		return strLineVer.substring(strLineVer.indexOf("Ver ") + 4).trim() + " " + REVISION +
			strLineRev.substring(strLineRev.indexOf(":") + 2).trim();
	} catch(e) {
	}
}

//----------------------------------------------------------
// URU Package Version取得
function getPackageURUVersion() {
	try {
		var objFSO = WScript.CreateObject("Scripting.FileSystemObject");
		var objInput = objFSO.OpenTextFile(".\\ExUpInfo.xml", 1, false); // readOnlyでOpen

		var strLineBuf;
		while(!objInput.AtEndOfLine) {
			strLineBuf = objInput.ReadLine();
			if(strLineBuf.indexOf("<version>") != -1) {
				break;
			}
		}
		return strLineBuf.substring(strLineBuf.indexOf("<version>") + 9, strLineBuf.indexOf("</version>"));
	} catch(e) {
	}
}

//----------------------------------------------------------
// 応答ファイル出力
function outputXmlFile(filename, resultCode, cmp, version) {
	var objStream = WScript.CreateObject("ADODB.Stream");
	objStream.Charset = "UTF-8";
	objStream.LineSeparator = -1; // CRLF
	objStream.Open();

	objStream.WriteText("<?xml version='1.0' encoding='UTF-8'?>",1);
	objStream.WriteText("<Response>",1);
	objStream.WriteText("<result_code>" + resultCode + "</result_code>",1);
	objStream.WriteText("<data>",1);
	if(cmp != null) {
		objStream.WriteText("<cmp>" + cmp + "</cmp>",1);
	}
	if(version != null) {
		objStream.WriteText("<version>" + version + "</version>",1);
	}
	objStream.WriteText("</data>",1);
	objStream.WriteText("</Response>",1);

	try {
		var objOutput = objStream.SaveToFile(filename);
	} catch(e) {
	}

	objStream.Close();
}

//----------------------------------------------------------
// ２重起動防止チェック (true:２重起動してない)
function duplexCheck() {
	var strComputer = ".";
	var objWMIService = GetObject("winmgmts:\\\\" + strComputer + "\\root\\cimv2");
	var colItems = objWMIService.ExecQuery("Select * From Win32_Process " +
		"Where Caption='cscript.exe' or Caption='wscript.exe'");

	var list = new Enumerator(colItems);

	var duplexCount = 0;
	for(; !list.atEnd(); list.moveNext()) {
		if(list.item().CommandLine.indexOf(WScript.ScriptName) != -1) {
			duplexCount++;
		}
		if(duplexCount > 1) { // 自分自身を除いて
			return false;
		}
	}
	return true;
}

//----------------------------------------------------------
// デバッグ用ログファイル出力
function outputErrorLogFile(e) {
	try {
		var objFSO = WScript.CreateObject("Scripting.FileSystemObject");
		var objOutput = objFSO.OpenTextFile("uruSetup.log", 8, true);
		var strLineVer = objOutput.WriteLine(e + "\n" );
		var strLineVer = objOutput.WriteLine(e.description + "\n");
		var strLineRev = objOutput.WriteLine(e.message + "\n");
		objOutput.close();
	} catch(e2) {
	}
}

//----------------------------------------------------------
// mmc.exe,raidview.exe,raidcmd.exe,rlogview.exe 起動チェック (true:起動してない)
function CheckClientLaunched() {
	var strComputer = ".";
	var objWMIService = GetObject("winmgmts:\\\\" + strComputer + "\\root\\cimv2");
	var colItems = objWMIService.ExecQuery("Select * From Win32_Process " +
		"Where Caption='mmc.exe' or Caption='raidview.exe' " +
		"or Caption='raidcmd.exe' or Caption='rlogview.exe'");

    if(colItems.Count > 0) { // どれか一つでも起動している場合
        return false;
    }

	return true;
}


//----------------------------------------------------------
// メイン処理
// 引数取り出し
var args = WScript.Arguments;

if(args.length == 0) {
	// 引数無しはQuit
	WScript.Quit();
}

// mmc.exe、raidview.exe、raidcmd.exe、rlogview.exeの起動チェック
if(!CheckClientLaunched()){
	switch(args(0)) {
	case UPDATE_NORMAL_ARG:
		outputXmlFile(UPDATE_NORMAL_FILENAME, "uru_update_err", null, null);
		WScript.Quit();
	case UPDATE_FORCE_ARG:
		outputXmlFile(UPDATE_FORCE_FILENAME, "uru_update_err", null, null);
		WScript.Quit();
	case UNINSTALL_ARG:
		outputXmlFile(UNINSTALL_FILENAME, "uru_uninst_err", null, null);
		WScript.Quit();
	default:
		break;
	}
}

// ２重起動チェック
if(!duplexCheck()) {
	switch(args(0)) {
	case GET_VERSION_ARG:
		outputXmlFile(GET_VERSION_FILENAME, "Busy", null, null);
		break;
	case UPDATE_NORMAL_ARG:
		outputXmlFile(UPDATE_NORMAL_FILENAME, "Duplex", null, null);
		break;
	case UPDATE_FORCE_ARG:
		outputXmlFile(UPDATE_FORCE_FILENAME, "Duplex", null, null);
		break;
	case INSTALL_ARG:
		outputXmlFile(INSTALL_FILENAME, "Duplex", null, null);
		break;
	case UNINSTALL_ARG:
		outputXmlFile(UNINSTALL_FILENAME, "Duplex", null, null);
		break;
	default:
		break;
	}
	WScript.Quit();
}

// パッケージのURU Version取得
var uruNewVersion = getPackageURUVersion();

// インストール済みURU Version取得
var uruCurrentVersion = getCurrentURUVersion();

// 新旧バージョン比較
var resultCmp = null;
if(uruCurrentVersion != null && uruNewVersion != null) {
	if(uruCurrentVersion.slice(0, uruCurrentVersion.indexOf(REVISION))
		== uruNewVersion.slice(0, uruNewVersion.indexOf(REVISION))) {
		// リビジョン比較
		if(uruCurrentVersion.substring(uruCurrentVersion.indexOf(REVISION) + REVISION.length)
			== uruNewVersion.substring(uruNewVersion.indexOf(REVISION) + REVISION.length)) {
			resultCmp = "Even";
		} else if(uruCurrentVersion.substring(uruCurrentVersion.indexOf(REVISION) + REVISION.length)
			< uruNewVersion.substring(uruNewVersion.indexOf(REVISION) + REVISION.length)) {
			resultCmp = "Upper";
		} else {
			resultCmp = "Lower";
		}
	} else if( uruCurrentVersion.slice(0, uruCurrentVersion.indexOf(REVISION))
		< uruNewVersion.slice(0, uruNewVersion.indexOf(REVISION))) {
		resultCmp = "Upper";
	} else {
		resultCmp = "Lower";
	}
}
// "/nomgr"確認
var installOpt = "";
if(!isDirExist(objShell.ExpandEnvironmentStrings("%AXIS2C_HOME%") + "\\bin\\AgentFolder\\raidsrv_agent")) {
	installOpt = " /nomgr";
}

// "/noviewer"確認
if(!isDirExist(objShell.ExpandEnvironmentStrings("%URAIDUTLPATH%") + "\\gui")) {
	installOpt = installOpt + " /noviewer";
}

try {
	switch(args(0)) {
	case GET_VERSION_ARG:
		if(uruCurrentVersion == null) {
			outputXmlFile(GET_VERSION_FILENAME, "Not-install", null, null);
		} else if(uruCurrentVersion.slice(0, uruCurrentVersion.indexOf(REVISION)) < 2.40) {
			outputXmlFile(GET_VERSION_FILENAME, "Not-install", null, null);
		} else {
			outputXmlFile(GET_VERSION_FILENAME, "OK", resultCmp, uruCurrentVersion);
		}
		break;
	case UPDATE_NORMAL_ARG:
		if(uruCurrentVersion == null) {
			outputXmlFile(UPDATE_NORMAL_FILENAME, "NotInstalled", null, null);
		} else if(uruCurrentVersion.slice(0, uruCurrentVersion.indexOf(REVISION)) < 2.40) {
			// バージョンが2.40未満の場合、処理を終了する。
			outputXmlFile(UNINSTALL_FILENAME, "NotInstalled", null, null);
		} else if(resultCmp != "Upper") {
			outputXmlFile(UPDATE_NORMAL_FILENAME, "DownGrade", null, null);
		} else {
			outputXmlFile(UPDATE_NORMAL_FILENAME, "OK", null, null);
			objShell.Run("\"" + objShell.CurrentDirectory + "\\windows\\Setup.exe\" /uninst /eua", 0, true);
			objShell.Run("\"" + objShell.CurrentDirectory + "\\windows\\Setup.exe\" /s /eua /transcfg" + installOpt, 0, true);
			outputXmlFile(UPDATE_NORMAL_FILENAME, "Complete", null, null);
		}
		break;
	case UPDATE_FORCE_ARG:
		if(uruCurrentVersion == null) {
			outputXmlFile(UPDATE_FORCE_FILENAME, "NotInstalled", null, null);
		} else if(uruCurrentVersion.slice(0, uruCurrentVersion.indexOf(REVISION)) < 2.40) {
			// バージョンが2.40未満の場合、処理を終了する。
			outputXmlFile(UPDATE_FORCE_FILENAME, "NotInstalled", null, null);
		} else {
			outputXmlFile(UPDATE_FORCE_FILENAME, "OK", null, null);
			objShell.Run("\"" + objShell.CurrentDirectory + "\\windows\\Setup.exe\" /uninst /eua", 0, true);
			objShell.Run("\"" + objShell.CurrentDirectory + "\\windows\\Setup.exe\" /s /eua /transcfg" + installOpt, 0, true);
			outputXmlFile(UPDATE_FORCE_FILENAME, "Complete", null, null);
		}
		break;
	case INSTALL_ARG:
		if(uruCurrentVersion != null) {
			outputXmlFile(INSTALL_FILENAME, "AlreadyInstalled", null, null);
		} else {
			outputXmlFile(INSTALL_FILENAME, "OK", null, null);
			objShell.Run("\"" + objShell.CurrentDirectory + "\\windows\\Setup.exe\" /s /eua", 0, true);
			outputXmlFile(INSTALL_FILENAME, "Complete", null, null);
		}
		break;
	case UNINSTALL_ARG:
		if(uruCurrentVersion == null) {
			outputXmlFile(UNINSTALL_FILENAME, "NotInstalled", null, null);
		} else if(uruCurrentVersion.slice(0, uruCurrentVersion.indexOf(REVISION)) < 2.40) {
			// バージョンが2.40未満の場合、処理を終了する。
			outputXmlFile(UNINSTALL_FILENAME, "NotInstalled", null, null);
		} else {
			outputXmlFile(UNINSTALL_FILENAME, "OK", null, null);
			if(uruCurrentVersion.slice(0, uruCurrentVersion.indexOf(REVISION)) == 2.40) {
				objShell.Run("\"" + uruUninstallerPath() + "\setup.exe\" /s /f1\"" +
					objShell.CurrentDirectory + "\\setup.iss\"", 0, true);
			} else {
				objShell.Run("\"" + uruUninstallerPath() + "\setup.exe\" /uninst", 0, true);
			}
			outputXmlFile(UNINSTALL_FILENAME, "Complete", null, null);
		}
		break;
	default:
		break;
	}
} catch(e) {
	outputErrorLogFile(e);
}

WScript.Quit();
