: ------------------------------------------------------------------
: Release Date: 2023-09-25
: commit hash: e79e6d83
: ------------------------------------------------------------------


: ------------------------------------------------------------------
:                           Changelog
: ------------------------------------------------------------------
: Date: 2023-06-21                                               
: Author: Ken Chan                                               
: Change: initial version                                        
: ------------------------------------------------------------------
: Date: 2023-07-04
: Author: Ken Chan
: Change:   1) updated download path
:           2) support download dataApiDLL.dll and WAPIWrapperCpp.dll
:           3) check if user have admin right & excel.exe is running
:           4) directly overwrite old version if exist
: ------------------------------------------------------------------      
: Date: 2023-07-23
: Author: Ken Chan
: Change:   1) Download and unzip the zip of dll according to 
:              the bitness of excel
: ------------------------------------------------------------------             
: Date: 2023-08-08
: Author: Ken Chan
: Change:   1) Update locale to zh_CN
: ------------------------------------------------------------------  
: Date: 2023-09-20
: Author: Ken Chan
: Change:   1) Update handling of 32 & 64 bit bloomberg dll
:           2) Update dataApiDLL.dll naming to QPRLib_dataApi.dll
: ------------------------------------------------------------------
: Date: 2023-09-25
: Author: Ken Chan
: Change:   1) logic refectoring - simplified the download logic
:           2) support redownload in insecure connection if SSL 
:              download failed
: ------------------------------------------------------------------
: Date: 2023-11-12
: Author: Ken Chan
: Change:   1) include EmQuantAPI and EmQuantAPI_x64
:           2) update install path to %system_excel_path%QPRLib\ and
:              register %system_excel_path%QPRLib\ to system path
: ------------------------------------------------------------------

echo off

echo ------------------------------------------------------------------
echo                   QPRLib Installation Script                    
echo ------------------------------------------------------------------
echo   This script will automatically install QPRLib Excel 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 excel.         
echo ------------------------------------------------------------------
echo.




: ------------------------------------------------------------------
:   Variables and constants
: ------------------------------------------------------------------

: enable delay expansion
setlocal enabledelayedexpansion

: online file path

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

rem set QPRLib_zip_path="https://dl.dropboxusercontent.com/scl/fi/avc9jt60voithxj35cgue/QPRLib.zip?rlkey=5734hxmqcl9agpxlbjxfm8r1s^&st=jt8wg005"

set QPRLib_zip_path="https://www.polyu.edu.hk/rcqf/qprlib_files/QPRLib.zip"

rem set QPRLib_zip_path="https://my.microsoftpersonalcontent.com/personal/67ea15c2f04736b3/_layouts/15/download.aspx?UniqueId=ebfe1050-634b-4824-ade5-5d43a97e2124^&Translate=false^&tempauth=v1e.eyJzaXRlaWQiOiI3YWU2ZmMzYS04NTBkLTQ0MGYtODQxNi0wZmZhOWFhOGY3YmIiLCJhcHBpZCI6IjAwMDAwMDAwLTAwMDAtMDAwMC0wMDAwLTAwMDA0ODE3MTBhNCIsImF1ZCI6IjAwMDAwMDAzLTAwMDAtMGZmMS1jZTAwLTAwMDAwMDAwMDAwMC9teS5taWNyb3NvZnRwZXJzb25hbGNvbnRlbnQuY29tQDkxODgwNDBkLTZjNjctNGM1Yi1iMTEyLTM2YTMwNGI2NmRhZCIsImV4cCI6IjE3MjA3NTk0NDcifQ.rkFKKXTaxEVHf9j5WziN-jChdUfgQqRJwrvkhroLqPOHoGE3nF-QMmjjMNnF6v8q_W_bCKPe02s5zLFTqxSEeZh8Y5-YDIFCdtSzwFrGZlPjawDBWLyfBIuf3Dcb8NERnq9SAcA2tc4h6IAu364PiRN6s_9sXMSNQYyZwt-cNMy9D477vtFn72uIEi0JtDzXxnjXMTILfuu_NYIEfpbh91JwwlZZrg3wn285rJnlhlqoYRFORkxKuwT2Uvqv2DAAm3k8GwZ9QZPCT4H4OCdAd4MqxfmR5hKXsc65Gzg2Be99iEsIfneH_RpOGlBIJvQEOprgHCYrls7BGGcqHkxnyjU1lFiWCqTShj5Ix34jUrmUd7JHKeOlBNX2AcQZcGUN10tG9ZKhTGG3fqY5IPVwIg.WFPhSy4Wb-bcPnn63IboVB6KX7bcxw7oNCZmram0A-Q^&ApiVersion=2.0^&AVOverride=1"

: value to store bitness of excel
set excel_bitness=32

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

: 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


: ------------------------------------------------------------------
:   Checking before installation
: ------------------------------------------------------------------

: check if the script is 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
)

: store the value of the registry key of HKEY_CLASSES_ROOT\Excel.Application\CurVer
: to variable excel_version
: if the registry key does not exist, exit the script

for /f "tokens=3" %%i in ('reg query HKEY_CLASSES_ROOT\Excel.Application\CurVer') do set full_ver=%%i
set excel_version=!full_ver:Excel.Application.=!

: for wps office debug purpose. can be removed in release version
echo [DBG]: ========= excel exe path =========
for /f "delims=" %%i in ('REG QUERY "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\winword.exe"') do (
    echo %%i
)
echo [DBG]: ========= excel exe path =========


: if the registry key does not exist, exit the script
if "%excel_version%"=="" (
    echo [ERROR]: Excel not found. Cannot proceed installation. Aborting...
    set ret=%RET_FAIL_EXCEL_NOT_FOUND%
    goto :endScript
)
echo [INFO]: excel version: !excel_version!

: check if excel.exe is running
echo [INFO]: checking if excel.exe is running...
tasklist /FI "IMAGENAME eq excel.exe" 2>NUL | find /I /N "excel.exe">NUL
if "%ERRORLEVEL%"=="0" (
    echo [ERROR]: excel.exe is running. Please close Excel and try again. Aborting...

    : set return value to RET_EXCEL_RUNNING
    set ret=%RET_EXCEL_RUNNING%
    goto :endScript
) else (
    echo [INFO]: excel.exe is not running.
)


: check if the excel is 32 bit or 64 bit
: logic: First check the system is 32 bit or 64 bit by systeminfo command
: if return "x64-based PC", then the system is 64 bit
: if return "x86-based PC", then the system is 32 bit
echo [INFO]: Obtaining system bitness...

:: 检查 wmic 命令是否可用
where wmic >nul 2>nul
if %errorlevel% equ 0 (
    for /f "tokens=2 delims==" %%i in ('wmic CPU get AddressWidth /value 2^>nul') do set system_env=%%i
)

:: 如果 wmic 不存在或没获取到值，使用备用方案
if "!system_env!"=="" (
    echo wmic not found, using systeminfo...
    :: 这种方法不需要调用任何外部 .exe 工具，绝对不会报错
    if /i "%PROCESSOR_ARCHITECTURE%"=="AMD64" (
        set system_env=64
    ) else if /i "%PROCESSOR_ARCHITEW6432%"=="AMD64" (
        set system_env=64
    ) else (
        set system_env=32
    )
)


: if failed to get system info, exit the script
if "!system_env!"=="" (
    echo [ERROR]: Failed to obtain system bitness. Aborting...
    set ret=%RET_FAIL_TO_OBTAIN_SYSTEM_BITNESS%
    goto :endScript
)

echo [INFO]: system bitness is: "%system_env%"



: if the system is 32 bit, then the excel must be 32 bit
if "%system_env%"=="32" (
    echo [INFO]: system is 32 bit, excel must be 32 bit
    set excel_bitness=32
) else (
    echo [INFO]: system is 64 bit, check 32 bit registery in WOW6432Node

    set pathfound=0
    set InstallRoot=""
        
    : checking 32 bit excel
    for /f "tokens=1*" %%a in ('reg query HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\Office') do (
        if !pathfound!==0 (
            set "key=%%a"
            : echo [INFO]: checking: !key!
            set "InstallRoot="
            for /f "tokens=2*" %%a in ('reg query "!key!\Excel\InstallRoot" /v Path 2^>nul') do set InstallRoot=%%b
            If "!InstallRoot!"=="" (
                @REM echo [INFO]: InstallRoot not found
            ) else (
                echo [INFO]: checking "%%a" : "!InstallRoot!" 
                : check if EXCEL.EXE exists in the path
                if exist "!InstallRoot!\EXCEL.EXE" (
                    echo [INFO]: EXCEL.EXE found. the excel is 32 bit
                    set pathfound=1
                    set excel_bitness=
                ) else (
                    echo [INFO]: EXCEL.EXE not found. 
                    set pathfound=0
                )
            )
        )
    )

    if !pathfound! == 0 (
        echo [INFO]: excel install root in WOW6432Node not found, search 64 bit registery.
    )

    : checking 64 bit excel
    for /f "tokens=1*" %%a in ('reg query HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Office') do (
        if !pathfound!==0 (
            set "key=%%a"
            : echo [INFO]: checking: !key!
            set "InstallRoot="
            for /f "tokens=2*" %%a in ('reg query "!key!\Excel\InstallRoot" /v Path 2^>nul') do set InstallRoot=%%b
            If "!InstallRoot!"=="" (
                @REM echo [INFO]: InstallRoot not found
            ) else (
                echo [INFO]: checking "%%a" : "!InstallRoot!" 
                : check if EXCEL.EXE exists in the path
                if exist "!InstallRoot!\EXCEL.EXE" (
                    
                    echo [INFO]: EXCEL.EXE found. the excel is 64 bit
                    set pathfound=1
                    set excel_bitness=64
                ) else (
                    echo [INFO]: EXCEL.EXE not found. 
                    set pathfound=0
                )
            )
        )
    )

    if "!pathfound!"=="0" (
        echo [ERROR]: excel install root not found. Cannot proceed installation. Aborting...
        set ret=%RET_FAIL_EXCEL_NOT_FOUND%
        goto :endScript
    )
    
) 
 
: ------------------------------------------------------------------
:   Step 1: Download Addin file online
: ------------------------------------------------------------------

: 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 QPRLib.xll and QPRLibRibbon.xlam...
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
)

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

echo [INFO]: unzip %excel_bitness% bit 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 ------------------------------------------------------------



: ------------------------------------------------------------------
:   Step 2: Search all xlstart folder
: ------------------------------------------------------------------

: find the xlstart folder path. find from appdata\Microsoft\Excel\XLSTART first
echo [INFO]: finding the xlstart folder path...

: Reference: https://support.microsoft.com/en-us/office/automatically-open-a-specific-workbook-or-template-when-you-start-excel-be9cddc1-a148-4cbf-8f3b-779df08957a3
: it is either C:\Users\(User name)\AppData\Microsoft\Excel\XLSTART (user path) 
: or C:\Program Files\Microsoft Office\Root\OfficeXX\XLSTART (system path, require admin permission)

: get the user path
set "user_excel_path=%appdata%\Microsoft\Excel\"
: get the system path by checking reg query "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\winword.exe" /v Path

FOR /F "usebackq skip=2 tokens=1,2*" %%A IN (`REG QUERY "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\winword.exe" /v Path 2^>nul`) DO (
    set ValueName=%%A
    set ValueType=%%B
    set system_excel_path=%%C
)
echo [INFO]: user excel path: "%user_excel_path%"
echo [INFO]: system excel path: "%system_excel_path%"

: if user path exists, use user path, else use system path. if both not exists, exit the script
set xl_path = ""
if exist "%user_excel_path%" ( 
    set "xl_path=%user_excel_path%"
) else (
    set "xl_path=%system_excel_path%"
)

if "%xl_path%"=="" (
    echo [ERROR]: Cannot find the xl folder. Aborting...
    echo ------------------------------------------------------------
    set ret=%RET_XL_NOT_FOUND% 
    goto :endScript
)

set "xlstart_path=%xl_path%XLSTART\"
echo [INFO]: xlstart folder path to be installed: "%xlstart_path%"

set "system_xlstart_path=%system_excel_path%XLSTART\"
echo [INFO]: system xlstart folder path: "%system_xlstart_path%"
echo ------------------------------------------------------------

: check xlstart folder exists. if not, create it
if not exist "%xlstart_path%" (
    echo [INFO]: xlstart folder not found. creating xlstart folder...
    mkdir "%xlstart_path%"
    echo [INFO]: xlstart folder created.
)

: ------------------------------------------------------------------
:  Step 3: Delete previous QPRLib.xll and QPRLib.xlam
: ------------------------------------------------------------------


: 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 "%xlstart_path%QPRLib64.xll" (
    echo [INFO]: QPRLib64.xll already exists in "%xlstart_path%". Deleting it...
    del "%xlstart_path%QPRLib64.xll"
    echo [INFO]: QPRLib64.xll deleted.
)

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

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

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

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

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


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

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


: also check QPRLib_dataApi.dll, WAPIWrapperCpp.dll, mysqlcppconn-9-vs14.dll, libcrypto-3-x64.dll, libssl-3-x64.dll in system excel folder
if exist "%system_excel_path%QPRLibDataAPI64.dll" (
    echo [INFO]: QPRLibDataAPI64.dll already exists in "%system_excel_path%". Deleting it...
    del "%system_excel_path%QPRLibDataAPI64.dll"
    echo [INFO]: QPRLibDataAPI64.dll deleted.
)

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


: remove EmQuantAPI.dll regardless of excel bitness. Wrong bitness dll in system excel folder might cause excel crash
if exist "%system_excel_path%EmQuantAPI.dll" (
    echo [INFO]: EmQuantAPI.dll already exists in "%system_excel_path%". Deleting it...
    del "%system_excel_path%EmQuantAPI.dll"
    echo [INFO]: EmQuantAPI.dll deleted.
)

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




: also check QPRLibDataAPI64.dll, QPRLibDataAPI.dll, EmQuantAPI_x64.dll, EmQuantAPI.dll in system excel folder
if exist "%system_excel_path%QPRLib\QPRLibDataAPI64.dll" (
    echo [INFO]: QPRLibDataAPI64.dll already exists in "%system_excel_path%QPRLib\". Deleting it...
    del "%system_excel_path%QPRLib\QPRLibDataAPI64.dll"
    echo [INFO]: QPRLibDataAPI64.dll deleted.
)

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


: remove EmQuantAPI.dll regardless of excel bitness. Wrong bitness dll in system excel folder might cause excel crash
if exist "%system_excel_path%QPRLib\EmQuantAPI.dll" (
    echo [INFO]: EmQuantAPI.dll already exists in "%system_excel_path%QPRLib\". Deleting it...
    del "%system_excel_path%QPRLib\EmQuantAPI.dll"
    echo [INFO]: EmQuantAPI.dll deleted.
)

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


: ------------------------------------------------------------------
:   Step 4: Copy QPRLib.xll and QPRLib.xlam
: ------------------------------------------------------------------
 

: copy QPRLib.xll and QPRLib.xlam to xlstart folder




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

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

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


echo ------------------------------------------------------------
echo [INFO]: creating QPRLib folder under excel path : %system_excel_path%QPRLib\
mkdir "%system_excel_path%QPRLib\"
echo [INFO]: QPRLib folder %system_excel_path%QPRLib\ created.
echo ------------------------------------------------------------


: copy QPRLib_dataApi and WAPIWrapperCpp to system excel folder
echo [INFO]: copying QPRLibDataAPI64 to %system_excel_path%QPRLib\...
copy /y %temp_install_path%QPRLibDataAPI64.dll "%system_excel_path%QPRLib\"
echo [INFO]: QPRLibDataAPI64.dll copied.

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


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

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



echo ------------------------------------------------------------

: ------------------------------------------------------------------
:   Step 5: Add %system_excel_path%QPRLib\ to system path
: ------------------------------------------------------------------

: check if %system_excel_path%QPRLib\ is already in system path. if not, add it
echo [INFO]: checking if %system_excel_path%QPRLib\ is already in system path...
set "pathfound=0"
for %%A in ("%path:;=" "%") do (
    if /I "%%~A"=="%system_excel_path%QPRLib\" (
        set "pathfound=1"
    )
)

if %pathfound%==1 (
    echo [INFO]: %system_excel_path%QPRLib\ already in system path.
) else (
    echo [INFO]: adding %system_excel_path%QPRLib\ to system path...
    setx path "%system_excel_path%QPRLib\;%path%" /M
    echo [INFO]: %system_excel_path%QPRLib\ added to system path.
)
echo ------------------------------------------------------------

: ------------------------------------------------------------------
:   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_EXCEL_NOT_FOUND, prompt error message and exit
    if %ret%==%RET_FAIL_EXCEL_NOT_FOUND% (
        echo.
        echo ------------------------------------------------------------------
        echo                        Installation Failed                        
        echo ------------------------------------------------------------------
        echo   Cannot detect Excel installation. 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_XL_NOT_FOUND, prompt error message and exit
    if %ret%==%RET_XL_NOT_FOUND% (
        echo.
        echo ------------------------------------------------------------------
        echo                        Installation Failed                        
        echo ------------------------------------------------------------------
        echo   Cannot find the excel 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 
    )

    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