@echo off
pushd %~dp0
setlocal enabledelayedexpansion

rem My architecture set. AMD64 or x86
set MYARCH=AMD64
rem Set product. X or XSSS
set PRODUCT=XSSS

set PARAM1=%~1
set PARAM2=%~2
set PARAM3=%~3
set PARAM4=%~4
set PARAM5=%~5

rem Parameter check
if /i "%PARAM1%"=="-i" (
	set ISSPATH=!PARAM2!
	if "!ISSPATH!"=="" goto USAGE
	if not exist "!ISSPATH!" (
		echo  ISS-file path is not exist.
		echo.
		goto EXIT
	)
	if /i "%PARAM3%"=="-l" (
		set LOGPATH=!PARAM4!
		if "!LOGPATH!"=="" goto USAGE
		set LOGPATH=%~dp4
		if not exist !LOGPATH!NUL (
			echo  Setup-log path is not exist.
			echo.
			goto EXIT
		)
		set LOGPATH=!PARAM4!
		set CHECK=!PARAM5!
	) else (
		set LOGPATH=%TEMP%\uninstall.log
		set CHECK=!PARAM3!
	)
) else (
	if /i "%PARAM1%"=="-l" (
		set LOGPATH=!PARAM2!
		if "!LOGPATH!"=="" goto USAGE
		set LOGPATH=%~dp2
		if not exist !LOGPATH!NUL (
			echo  Setup-log path is not exist.
			echo.
			goto EXIT
		)
		set LOGPATH=!PARAM2!
		set CHECK=!PARAM3!
	) else (
		set LOGPATH=%TEMP%\uninstall.log
		set CHECK=!PARAM1!
	)
)
if not "%CHECK%"=="" goto USAGE

rem iss-file select
set CURPATH=%~dp0
if "%ISSPATH%"=="" (
	for /f "tokens=2 delims=:" %%p in ('chcp') do (
		set CODEPAGE=%%p
	)
	if /i "%PRODUCT%"=="X" (
		if "!CODEPAGE!"==" 932" (
			rem Japanese
			set ISSPATH=!CURPATH!response\setup_uninst_jp.iss
		) else if "!CODEPAGE!"==" 936" (
			rem Chinese
			set ISSPATH=!CURPATH!response\setup_uninst_cn.iss
		) else (
			rem English
			set ISSPATH=!CURPATH!response\setup_uninst_en.iss
		)
	) else if /i "%PRODUCT%"=="XSSS" (
		if "!CODEPAGE!"==" 932" (
			rem Japanese
			set ISSPATH=!CURPATH!response\setup_sss_uninst_jp.iss
		) else if "!CODEPAGE!"==" 936" (
			rem Chinese
			set ISSPATH=!CURPATH!response\setup_sss_uninst_cn.iss
		) else (
			rem English
			set ISSPATH=!CURPATH!response\setup_sss_uninst_en.iss
		)
	) else (
		echo  Product error.
		echo  Silent uninstall was failed.
		goto ERROR
	)
	if not exist "!ISSPATH!" (
		echo  ISS-file path is not exist.
		echo.
		goto EXIT
	)
)

rem Add double quotation
set ISSPATH="%ISSPATH%"
set LOGPATH="%LOGPATH%"

if /i "%PROCESSOR_ARCHITECTURE%"=="%MYARCH%" (
	start "title" /wait "%CURPATH%setup.exe" /s /f1!ISSPATH! /f2!LOGPATH!
	rem check return code
	for /f "tokens=2 delims==" %%2 in ('findstr "ResultCode=" !LOGPATH!') do (
		set /A RESULT=%%2
	)
	if !RESULT!==0 (
		echo  Silent uninstall was succeeded.
	) else (
		echo  Silent uninstall was failed. code=!RESULT!
	)
	rem del
	del !LOGPATH! >NUL 2>&1
) else (
	goto ERROREXIT
)


:NORMALEXIT
exit /b !RESULT!

:ERROREXIT
echo  Architecture is not correct.
echo  Silent uninstall was failed.
exit /b 1

:USAGE
echo  Invalid parameter.
echo. 
echo  usage:
echo  silent-uninstall.bat [-i "ISS-file path"] [-l "setup-log path"]
exit /b 1

:EXIT
exit /b 1
