@echo off


echo ------------------------------------------------------------------
echo                   QPRLib Installation Script                    
echo ------------------------------------------------------------------
echo   This script will automatically install QPRLib WPS Add-in to  
echo   the user's computer. The script will download the corresponding 
echo   binary file to the xlstart folder. The script will also update
echo   the system locale to zh_CN to avoid Mojibake due to wrong 
echo   decoding in WPS.         
echo ------------------------------------------------------------------
echo.

setlocal enabledelayedexpansion


:: ----------------------add-in download website--------------------------
set QPRLib_zip_path="https://www.polyu.edu.hk/rcqf/qprlib_files/QPRLib.zip"
:: ----------------------add-in download website--------------------------

rem set QPRLib_zip_path="https://drive.google.com/uc?export=download^&id=1X4Jt82Zw3DUbS6gZo4La3sNFBuNIclcX"

:: ----------------------variables & return value--------------------------
: return value variable of the script
set ret=0

: return value

: success - 0
set RET_SUCCESS=0

: failed in checking before installation: 100x
set RET_FAIL_EXCEL_NOT_FOUND=1001
set RET_EXCEL_RUNNING=1002
set RET_NO_ADMIN_RIGHT=1003
set RET_FAIL_TO_OBTAIN_SYSTEM_BITNESS=1004

: failed during installation: 200x
set RET_FAIL_DOWNLOAD=2001
set RET_FAIL_UNZIP=2002
set RET_XL_NOT_FOUND=2003

: temp folder path for installation. create a new folder under temp folder with a random name
set temp_install_path=%temp%\QPRLib_%RANDOM%\
:: ----------------------variables & return value--------------------------

:: ----------------------check 1(running as administrator)-----------------
echo [INFO]: checking if the script is running as administrator...
net session >nul 2>&1
if %errorLevel% == 0 (
    echo [INFO]: Script is running as administrator.
) else (
    echo [ERROR]: Script is not running as administrator. Aborting...
    set ret=!RET_NO_ADMIN_RIGHT!
    goto :endScript
)



:: ----------------------check 2(wps has installed)------------------------
reg query "HKEY_LOCAL_MACHINE\SOFTWARE\Kingsoft\Office\6.0\Common" >nul 2>&1
if %errorLevel% == 0 (
    echo [INFO]: WPS is found.
) else (
    echo [ERROR]: WPS is not found. Aborting...
    set ret=!RET_FAIL_EXCEL_NOT_FOUND!
    goto :endScript
)

:: ----------------------check 3(xlstart has found)------------------------
: find the xlstart folder path. find from appdata\Microsoft\Excel\XLSTART first
echo [INFO]: finding the xlstart folder path...

:: 寻找根目录及xlstart文件夹
set "installRoot="
rem XLSTART directory, used to save xll & xlam files
set xl_path = ""
rem et.exe directory, used to save dll files
set et_path = ""
for /f "skip=1 tokens=2,*" %%a in ('reg query "HKEY_LOCAL_MACHINE\SOFTWARE\Kingsoft\Office\6.0\Common" /v InstallRoot 2^>nul') do (
    set "installRoot=%%b"
    set "xl_path=%%b\office6\XLSTART\"
    set "et_path=%%b\office6\"
)

rem %xl_path%为什么需要加“”,是为了防止目录中存在空格
if exist "%xl_path%" ( 
    echo [INFO]: Find the xl folder.
) else (
    echo [ERROR]: Cannot find the xl folder. Aborting...
    echo ------------------------------------------------------------
    set ret=!RET_XL_NOT_FOUND! 
    goto :endScript
)

:: ----------------------check 4(wps table is running)---------------------
rem check whether the wps excel is running, shown as et.exe
tasklist | find /i "et.exe" > nul
if errorlevel 1 (
    rem echo et.exe is not running.
) else (
    echo [ERROR]: et.exe is running. Please close wps and try again. Aborting...
    set ret=!RET_EXCEL_RUNNING!
    goto :endScript
)

::---------------------download add-in and move to xlstart ----------------


: create temp folder for installation
echo [INFO]: creating temp folder for installation: %temp_install_path%
mkdir %temp_install_path%
echo [INFO]: temp_install_path %temp_install_path% created.
echo ------------------------------------------------------------

: CD to batch file path
cd /D "%~dp0"

: curl download all addin file and store to %temp%\QPRLib folder
echo [INFO]: downloading Addin files...
echo ------------------------------------------------------------

: check if curl is installed in system path
for %%X in (curl.exe) do (set sys_curl=%%~$PATH:X)

if defined sys_curl (
    echo [INFO]: curl local installation found. 
    set "curl_cmd=%sys_curl%"
) else (
    echo [INFO]: curl not installed in system, use curl.exe in script folder.
    set "curl_cmd=%~dp0curl\curl.exe"
)

set "QPRLib_zip_path=%QPRLib_zip_path%"
set "QPRLib_zip=%temp_install_path%QPRLib.zip"
set "QPRLib_folder=%temp_install_path%QPRLib"

rem echo [INFO]: excel is %excel_bitness% bit, download %excel_bitness% bit QPRLib.xll and QPRLib.xlam from %QPRLib_zip_path% ...
echo ------------------------------------------------------------
"%curl_cmd%" -L %QPRLib_zip_path% -o %QPRLib_zip%
if errorlevel 1 (
    echo [WARINING]: Download failed. Trying again insecure connection. 
    echo [WARINING]: You are advisied to cross check the downloaded content.
    echo ------------------------------------------------------------
    "%curl_cmd%" -k -L %QPRLib_zip_path% -o %QPRLib_zip%
)
echo ------------------------------------------------------------


: reset errorlevel to 0
: TODO: verify if it works
ver > nul


if not exist %QPRLib_zip% (
    echo [ERROR]: Cannot download %QPRLib_zip%. Aborting...
    echo ------------------------------------------------------------

    : set return value to RET_FAIL_DOWNLOAD
    set ret=！RET_FAIL_DOWNLOAD！
    goto :endScript
)

rem pause
rem : unzip success
rem echo [INFO]: QPRLib.xll and QPRLibRibbon.xlam unzipped successfully.
rem echo [INFO]: unzip %excel_bitness% bit QPRLib.xll and QPRLibRibbon.xlam...

echo [INFO]: unzip QPRLib.xll and QPRLibRibbon.xlam...
Call :UnZipFile "%temp_install_path%" "%QPRLib_zip%"

echo [INFO]: delete %QPRLib_zip%...
del %QPRLib_zip%

echo [INFO]: move all content from %QPRLib_folder% to %temp_install_path%...
move %QPRLib_folder%\* %temp_install_path%

echo [INFO]: delete %QPRLib_folder%...
rmdir /s /q %QPRLib_folder%

echo ------------------------------------------------------------
rem : check if unzip success
rem if not exist %temp_install_path%QPRLib.xll (
rem     echo [ERROR]: Cannot download QPRLib.xll. Aborting...
rem     echo ------------------------------------------------------------

rem     : set return value to RET_FAIL_UNZIP
rem     set ret=%RET_FAIL_UNZIP%
rem     goto :endScript
rem )

if not exist %temp_install_path%QPRLibRibbon.xlam (
    echo [ERROR]: Cannot download QPRLibRibbon.xlam. Aborting...
    echo ------------------------------------------------------------

    : set return value to RET_FAIL_UNZIP
    set ret=%RET_FAIL_UNZIP%
    goto :endScript
)

: unzip success
echo [INFO]: QPRLib.xll and QPRLibRibbon.xlam unzipped successfully.
echo ------------------------------------------------------------


: check if previous QPRLib.xll and QPRLib.xlam exists. if yes, delete it
echo [INFO]: checking if previous QPRLib.xll and QPRLibRibbon.xlam. Delete it exists...
echo ------------------------------------------------------------

if exist "%xl_path%QPRLib64.xll" (
    echo [INFO]: QPRLib64.xll already exists in "%xl_path%". Deleting it...
    del "%xl_path%QPRLib64.xll"
    echo [INFO]: QPRLib64.xll deleted.
)

if exist "%xl_path%QPRLib.xll" (
    echo [INFO]: QPRLib.xll already exists in "%xl_path%". Deleting it...
    del "%xl_path%QPRLib.xll"
    echo [INFO]: QPRLib.xll deleted.
)

if exist "%xl_path%QPRLibRibbon.xlam" (
    echo [INFO]: QPRLibRibbon.xlam already exists in "%xl_path%". Deleting it...
    del "%xl_path%QPRLibRibbon.xlam"
    echo [INFO]: QPRLibRibbon.xlam deleted.
)

if exist "%xl_path%QPRLib.xlam" (
    echo [INFO]: QPRLib.xlam already exists in "%xl_path%". Deleting it...
    del "%xl_path%QPRLib.xlam"
    echo [INFO]: QPRLib.xlam deleted.
)

if exist "%et_path%QPRLibDataAPI64.dll" (
    echo [INFO]: QPRLibDataAPI64.dll already exists in "%et_path%". Deleting it...
    del "%et_path%QPRLibDataAPI64.dll"
    echo [INFO]: QPRLibDataAPI64.dll deleted.
)

if exist "%et_path%QPRLibDataAPI.dll" (
    echo [INFO]: QPRLibDataAPI.dll already exists in "%et_path%". Deleting it...
    del "%et_path%QPRLibDataAPI.dll"
    echo [INFO]: QPRLibDataAPI.dll deleted.
)

if exist "%et_path%EmQuantAPI.dll" (
    echo [INFO]: EmQuantAPI.dll already exists in "%et_path%". Deleting it...
    del "%et_path%EmQuantAPI.dll"
    echo [INFO]: EmQuantAPI.dll deleted.
)

if exist "%et_path%EmQuantAPI_x64.dll" (
    echo [INFO]: EmQuantAPI_x64.dll already exists in "%et_path%". Deleting it...
    del "%et_path%EmQuantAPI_x64.dll"
    echo [INFO]: EmQuantAPI_x64.dll deleted.
)


echo [INFO]: copying QPRLibRibbon.xlam to %xl_path%...
copy /y %temp_install_path%QPRLibRibbon.xlam "%xl_path%"
echo [INFO]: QPRLibRibbon.xlam copied.

echo [INFO]: copying QPRLib64.xll to %xl_path%...
copy /y %temp_install_path%QPRLib64.xll "%xl_path%"
echo [INFO]: QPRLib64.xll copied.

echo [INFO]: copying QPRLib.xll to %xl_path%...
copy /y %temp_install_path%QPRLib.xll "%xl_path%"
echo [INFO]: QPRLib.xll copied.

echo [INFO]: copying QPRLibDataAPI64 to %et_path%...
copy /y %temp_install_path%QPRLibDataAPI64.dll "%et_path%"
echo [INFO]: QPRLibDataAPI64.dll copied.

echo [INFO]: copying QPRLibDataAPI to %et_path%QPRLib\...
copy /y %temp_install_path%QPRLibDataAPI.dll "%et_path%"
echo [INFO]: QPRLibDataAPI.dll copied.


echo [INFO]: copying EmQuantAPI_x64 to %et_path%...
copy /y %temp_install_path%EmQuantAPI_x64.dll "%et_path%"
echo [INFO]: EmQuantAPI_x64.dll copied.

echo [INFO]: copying EmQuantAPI to %et_path%...
copy /y %temp_install_path%EmQuantAPI.dll "%et_path%"
echo [INFO]: EmQuantAPI.dll copied.




:: step 6: Update System Locale to simplified Chinese


: check if system locale is simplified Chinese. if not, update it
echo [INFO]: checking system locale...

: use powershell command Get-WinSystemLocale to get system locale 
FOR /F "tokens=* USEBACKQ" %%F IN (`powershell -Command "Get-WinSystemLocale | Select-Object -ExpandProperty Name"`) DO (
   SET "system_locale=%%F"
)

IF "%system_locale%"=="" (
    echo [WARNING]: Failed to get system locale. Please check the system locale manually.
    echo ------------------------------------------------------------
    goto :endScript
)

SET updated_locale=0

: if system locale is not simplified Chinese, update it using powershell
If "%system_locale%"=="zh-CN" (
    echo [INFO]: system locale is simplified Chinese

    echo ------------------------------------------------------------
) else (
    echo [INFO]: system locale is not simplified Chinese, updating system locale to simplified Chinese...
    powershell -ExecutionPolicy Bypass -command "Set-WinSystemLocale -SystemLocale zh-CN" || (
        echo [WARNING]: Failed to update the system locale to simplified Chinese. Please update the system locale manually.
        echo ------------------------------------------------------------
        goto :endScript
    )
    echo [INFO]: system locale updated to simplified Chinese. Please restart the computer to take effect.
    echo ------------------------------------------------------------
    SET updated_locale=1
)



: ------------------------------------------------------------------
:   Prompt Result and Exit Script
: ------------------------------------------------------------------

:endScript
    : check if temp folder for installation exists. if yes, remove it
    if exist %temp_install_path% (
        echo [INFO]: removing temp folder for installation: %temp_install_path%
        rmdir /s /q %temp_install_path%
        echo [INFO]: temp_install_path %temp_install_path% removed.
    )

    : if ret = RET_SUCCESS, prompt success message and exit
    if %ret%==%RET_SUCCESS% (
        echo. 
        echo ------------------------------------------------------------------
        echo                      Installation Success                      
        echo ------------------------------------------------------------------
        echo   The Addin have been installed successfully. You may now close 
        echo   this window and start Excel. The Addin will be loaded         
        echo   automatically.                                                
        echo ------------------------------------------------------------------  
        echo.

        : if system locale is updated, prompt restart message
        if "%updated_locale%"=="1" (
            set restart_option=""
            Call :MessageBox "The System Locale have been set to zh_CN. You need to restart the machine to take effect. Do you want to restart now?" restart_option

            if "!restart_option!"=="y" (
                echo [INFO]: Restarting the machine...
                shutdown /r /t 0
            ) else (
                echo ------------------------------------------------------------------
                echo   The System Locale have been set to zh_CN. You may want to 
                echo   restart the machine to take effect.
                echo ------------------------------------------------------------------ 
            )
        )
        pause
        exit 
    )


    : if ret = RET_FAIL_UNZIP, prompt error message and exit
    if %ret%==%RET_FAIL_DOWNLOAD% (
        echo.
        echo ------------------------------------------------------------------
        echo                        Installation Failed                        
        echo ------------------------------------------------------------------
        echo   Cannot download the installation compressed file.                   
        echo   The Addin have NOT been installed. Please check the internet   
        echo   connection and try again. You may also contact us for further  
        echo   assistance. Aborted.                                           
        echo ------------------------------------------------------------------  
        echo.
        pause
        exit 
    )

    : if ret = RET_FAIL_UNZIP, prompt error message and exit
    if %ret%==%RET_FAIL_UNZIP% (
        echo.
        echo ------------------------------------------------------------------
        echo                        Installation Failed                        
        echo ------------------------------------------------------------------
        echo   Cannot unzip the installation compressed file.                   
        echo   The Addin have NOT been installed. Please check the internet   
        echo   connection and try again. You may also contact us for further  
        echo   assistance. Aborted.                                           
        echo ------------------------------------------------------------------  
        echo.
        pause
        exit 
    )

    : if ret = RET_FAIL_WPS_NOT_FOUND, prompt error message and exit
    if %ret%==%RET_FAIL_EXCEL_NOT_FOUND% (
        echo.
        echo ------------------------------------------------------------------
        echo                        Installation Failed                        
        echo ------------------------------------------------------------------
        echo   Cannot detect WPS installation. The Addin have not been      
        echo   installed. Please make sure WPS is installed and try again.  
        echo   You may also contact us for further assistance. Aborted.       
        echo ------------------------------------------------------------------
        echo.
        pause
        exit 
    )

    : if ret = RET_XL_NOT_FOUND, prompt error message and exit
    if %ret%==!RET_XL_NOT_FOUND! (
        echo.
        echo ------------------------------------------------------------------
        echo                        Installation Failed                        
        echo ------------------------------------------------------------------
        echo   Cannot find the wps xlstart folder. The Addin have not been           
        echo   installed. Please make sure Excel is installed and try again.  
        echo   You may also contact us for further assistance. Aborted.       
        echo ------------------------------------------------------------------
        echo.
        pause
        exit 
    )

    : if ret = RET_NO_ADMIN_RIGHT, prompt error message and exit
    if %ret%==!RET_NO_ADMIN_RIGHT! (
        echo.
        echo ------------------------------------------------------------------
        echo                        Installation Failed                        
        echo ------------------------------------------------------------------
        echo   Cannot install the Addin. Please run the script as administrator. 
        echo   You may also contact us for further assistance. Aborted.       
        echo ------------------------------------------------------------------
        echo.
        pause
        exit 
    )

    : if ret = RET_EXCEL_RUNNING, prompt error message and exit
    if %ret%==%RET_EXCEL_RUNNING% (
        echo.
        echo ------------------------------------------------------------------
        echo                        Installation Failed                        
        echo ------------------------------------------------------------------
        echo   Cannot install the Addin. Please close all Excel instances and 
        echo   try again. You may also contact us for further assistance.     
        echo   Aborted.                                                       
        echo ------------------------------------------------------------------
        echo.
        pause
        exit 
    )

    : if ret = RET_FAIL_TO_OBTAIN_SYSTEM_BITNESS, prompt error message and exit
    if %ret%==%RET_FAIL_TO_OBTAIN_SYSTEM_BITNESS% (
         echo.
        echo ------------------------------------------------------------------
        echo                        Installation Failed                        
        echo ------------------------------------------------------------------
        echo   The Script havs failed to determine system bitness environment.
        echo   please contact us for further assistance. Aborted.                                                       
        echo ------------------------------------------------------------------
        echo.
        pause
    )

    : other unknown error (ret != RET_SUCCESS), prompt error message and exit
    if not %ret%==RET_SUCCESS (
        echo.
        echo ------------------------------------------------------------------
        echo                      Installation Failed                        
        echo ------------------------------------------------------------------
        echo  Unknown error. The Addin have not been installed.              
        echo  Please contact us for further assistance. Aborted.             
        echo ------------------------------------------------------------------
        echo.
        pause
        exit 
    )

pause
exit



: auxilary functions

:UnZipFile <ExtractTo> <newzipfile>
set vbs="%temp%\_.vbs"
if exist %vbs% del /f /q %vbs%
>%vbs%  echo Set fso = CreateObject("Scripting.FileSystemObject")
>>%vbs% echo If NOT fso.FolderExists(%1) Then
>>%vbs% echo fso.CreateFolder(%1)
>>%vbs% echo End If
>>%vbs% echo set objShell = CreateObject("Shell.Application")
>>%vbs% echo set FilesInZip=objShell.NameSpace(%2).items
>>%vbs% echo objShell.NameSpace(%1).CopyHere(FilesInZip)
>>%vbs% echo Set fso = Nothing
>>%vbs% echo Set objShell = Nothing
cscript //nologo %vbs%
if exist %vbs% del /f /q %vbs%
exit /b

:MessageBox <message>
set vbs="%temp%\_.vbs"
set outFile="%temp%\result.txt"
if exist %vbs% del /f /q %vbs%
>%vbs% echo Set objArgs = WScript.Arguments
>>%vbs% echo messageText = objArgs(0)
>>%vbs% echo Set fso = CreateObject("Scripting.FileSystemObject")
>>%vbs% echo Set outFile = fso.CreateTextFile(objArgs(1), True)
>>%vbs% echo intButton = MsgBox(messageText, vbYesNo, "Confirmation")
>>%vbs% echo If intButton = vbYes Then
>>%vbs% echo outFile.WriteLine("y")
>>%vbs% echo Else
>>%vbs% echo outFile.WriteLine("n")
>>%vbs% echo End If
>>%vbs% echo outFile.Close
cscript //Nologo %vbs% "%~1" "%outFile%"
set /p %~2=<%outFile%
if exist %vbs% del /f /q %vbs%
if exist %outFile% del /f /q %outFile%
exit /b
