@echo off
echo off
setlocal EnableDelayedExpansion
rem -----------------------------------------------
rem this shell for an unified installation(window)
rem -----------------------------------------------

set /p HA_PROXY_IP=Please input the ip address:
if "!HA_PROXY_IP!" == "" (
    echo The IP address is empty.
    pause
    exit 1
)
if not exist %~dp0\conf (
    md %~dp0\conf
)
call :check_ip "%HA_PROXY_IP%" validity
if [%validity%] equ [0] (
    call :check_connect
) else (
    Color 0C
    echo "%HA_PROXY_IP%" is not a valid ip
    pause
    exit 1
)

set /p ACTIVATION_CODE_bak=Please input the activation code:
set ACTIVATION_CODE=%ACTIVATION_CODE_bak: =%
if not "%ACTIVATION_CODE%" == "%ACTIVATION_CODE_bak%" (
    echo "Please enter the correct activation code, Please check and try again"
    pause
    exit 1
)
set ACTIVE_CODE_LIST=a b c d e f 0 1 2 3 4 5 6 7 8 9
set COUNT_LIST=8 13 18 23
call :check_activation_code
call :check_length

set AGENT_ROOT=%~dp0
set /a FREE_SPACE_MIN=5120
set PYTHON_PATH=%AGENT_ROOT%\python3
set LOG_FILE="%AGENT_ROOT%/AgentAssist_install.log"
set LANGUAGE=English
set PROXY_PORT="8089"
call :select_language
call :select_dir

set INSTALL_PYTHON_PATH=%INSTALL_PATH%\AgentAssistPython
md %INSTALL_PYTHON_PATH%
XCOPY /s /e /y %PYTHON_PATH% %INSTALL_PYTHON_PATH% > nul

call :write_path

%INSTALL_PYTHON_PATH%\python.exe %AGENT_ROOT%\scripts\install.py "%HA_PROXY_IP%" "%ACTIVATION_CODE%" %LANGUAGE% %INSTALL_PATH%
if %errorlevel% == 1 (
    echo Failed to install the client assistant.
    pause
    exit /b 0
)

set KMC_KEYSTORE_PATH="c:\\huawei\\agentassist\\kmc\\conf"
set KMC_KEYSTORE_LOG_PATH="c:\\huawei\\agentassist\\kmc\\log"

call :mkdir_kmc_keystone_subagent_pkg

XCOPY /y "%INSTALL_PATH%\AgentAssist\conf\standby_keystore.txt"  %KMC_KEYSTORE_PATH%> nul
XCOPY /y "%INSTALL_PATH%\AgentAssist\conf\primary_keystore.txt" %KMC_KEYSTORE_PATH% > nul

cd %INSTALL_PATH%\AgentAssist
call update_ak_sk.bat
if %errorlevel% == 1 (
    echo Save access and secret fail.
	call uninstall.bat
	pause
	exit /b 1
)

call download_cert.bat %INSTALL_PATH% %HA_PROXY_IP%
if %errorlevel% == 1 (
    echo Download cert fail.
	call uninstall.bat
	pause
	exit /b 1
)

%INSTALL_PYTHON_PATH%\python.exe %INSTALL_PATH%\AgentAssist\bin\assist\connectivity.py %INSTALL_PATH% "%HA_PROXY_IP%" %PROXY_PORT%
if %errorlevel% == 1 (
    echo Connect to the server failed, please check whether the entered IP address is correct.
    call uninstall.bat
    pause
    exit /b 1
)

call start.bat
pause
exit /b 0

:mkdir_kmc_keystone_subagent_pkg

    if exist "%KMC_KEYSTORE_PATH%" (
        rd /s/q "c:\\huawei" > nul
    )

    if exist "%KMC_KEYSTORE_LOG_PATH%" (
        rd /s/q "c:\\huawei" > nul
    )

    md "%KMC_KEYSTORE_PATH%"
    md "%KMC_KEYSTORE_LOG_PATH%"

    goto :EOF

:check_connect
    echo "!HA_PROXY_IP!" | findstr "\." > nul && (
        set ip_type=IPV4
    ) || (
        echo "!HA_PROXY_IP!" | findstr "\:" > nul && (
            set ip_type=IPV6
        ) || (
            echo IP address ["!HA_PROXY_IP!"] is invalid.
            pause
            exit 1
        )
    )

    if "!ip_type!"=="IPV4"  (
        ping -4 "!HA_PROXY_IP!" -n 1 -w 3000 | findstr /r /c:"[0-9]*ms" > nul
    ) else (
        ping -6 "!HA_PROXY_IP!" -n 1 -w 3000 | findstr /r /c:"[0-9]*ms" > nul
    )

    if !ERRORLEVEL! NEQ 0 (
        echo The local computer cannot ping the "!HA_PROXY_IP!" address.
        exit /b 1
    )
    goto :EOF

:check_ip <IP> <validity>
    Set "VbsFile=%~dp0conf\%~n0.vbs"
    (
        echo WScript.Echo(Is_Valid("%~1"^)^)
        echo Function Is_Valid(ip^)
        echo    Dim RegularExpressionObject
        echo    Set RegularExpressionObject = New RegExp
        echo    With RegularExpressionObject
        echo        .Pattern = "(^((25[0-5]|2[0-4]\d|1?\d?\d)\.){3}(25[0-5]|2[0-4]\d|1?\d?\d)$)|((([0-9a-fA-F]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9a-fA-F]{1,4}:){6}((([0-9]{1,3}\.){3}[0-9]{1,4})|([0-9a-fA-F]{1,4})|:))|(([0-9a-fA-F]{1,4}:){5}:((([0-9a-fA-F]{1,4})?)|([0-9a-fA-F]{1,4}:[0-9a-fA-F]{1,4})|(([0-9]{1,3}\.){3}[0-9]{1,4})))|(([0-9a-fA-F]{1,4}:){4}:((([0-9a-fA-F]{1,4})?)|(([0-9a-fA-F]{1,4}:){1,2}[0-9a-fA-F]{1,4})|(([0-9a-fA-F]{1,4}:)?([0-9]{1,3}\.){3}[0-9]{1,4})))|(([0-9a-fA-F]{1,4}:){3}:((([0-9a-fA-F]{1,4}:){0,2}([0-9]{1,3}\.){3}[0-9]{1,4})|(([0-9a-fA-F]{1,4}:){0,3}[0-9a-fA-F]{1,4})|$))|(([0-9a-fA-F]{1,4}:){2}:((([0-9a-fA-F]{1,4}:){0,3}([0-9]{1,3}\.){3}[0-9]{1,4})|(([0-9a-fA-F]{1,4}:){0,4}[0-9a-fA-F]{1,4})|$))|(([0-9a-fA-F]{1,4}:){1}:((([0-9a-fA-F]{1,4}:){0,4}([0-9]{1,3}\.){3}[0-9]{1,4})|(([0-9a-fA-F]{1,4}:){0,5}[0-9a-fA-F]{1,4})|$))|(::((([0-9a-fA-F]{1,4}:){0,5}([0-9]{1,3}\.){3}[0-9]{1,4})|(([0-9a-fA-F]{1,4}:){0,6}[0-9a-fA-F]{1,4})|$)))$"
        echo        .IgnoreCase = False
        echo        If .Test(ip^)= True then
        echo            Is_Valid = 0
        echo        Else
        echo            Is_Valid = 1
        echo        End if
        echo    End With
        echo End Function
    )>"%VbsFile%"
    @for /f "delims=" %%a in ('cscript //nologo "%VbsFile%"') do set "%2=%%a"
    Exit /B

:select_language
    set try_count=5
    for %%i in (0, 1, 2, 3, 4) do (
        echo "  Please choose the language:        "
        echo "   [ (1)Chinese   |   (2)English ]   "
        echo "  Please input your choice. You have !try_count! chances. Please enter 1 or 2:"
        set /p language_select=

        if  "!language_select!" == "1" (
            set LANGUAGE=Chinese
            call :Log "The selected system language is !LANGUAGE!. "
            goto :EOF
        ) else if "!language_select!" == "2" (
            call :Log "The selected system language is !LANGUAGE!. "
            goto :EOF
        )
        echo The input value is invalid.
        set /a try_count-=1
    )
    call :Log "The number of incorrect inputs reaches 5. The default value !LANGUAGE! is used."
    echo The number of incorrect inputs reaches 5. The default value !LANGUAGE! is used.
    goto :EOF

:select_dir
    set try_count=5
    echo "Default installation address: C:\ "
    for %%i in (0, 1, 2, 3, 4) do (
        echo "Do you want to use the default address for installation? You have !try_count! chances. Please enter y or n:"
        set use_default_dir=
        set /p use_default_dir=
        call :Log "You choose is !use_default_dir! "

        if "!use_default_dir!" == "N" (
            set use_default_dir=n
        )

        if "!use_default_dir!" == "Y" (
            set use_default_dir=y
        )
        if "!use_default_dir!" == "n" (
            call :receive_install_address ret
            if "!ret!" == "success" (
                call :Log "The installation path is !INSTALL_PATH!."
                goto :EOF
            )
        ) else if "!use_default_dir!" == "y" (
              set INSTALL_PATH=C:\
              call :check_install_address ret
              if "!ret!" == "success" (
                  call :Log "Use the default installation address. INSTALL_PATH: !INSTALL_PATH!."
                  goto :EOF
                )
        ) else (
            echo The input value is invalid.
        )
        set /a try_count-=1
    )
    call :Log "The number of incorrect inputs reaches 5. The installation process exits."
    echo The number of incorrect inputs reaches 5. The installation process exits.
    exit 1

:receive_install_address
    echo "Please input the installation address."
    set input_dir=
    set /p input_dir=
    call :Log "The address entered by the user is: !input_dir!"
    if exist "!input_dir!" (
        set INSTALL_PATH=!input_dir!
        call :adjust_input_path
        call :check_install_address %~1
    ) else (
        echo The installation directory does not exist.
        set "%~1=failed"
    )
    goto :EOF

:check_install_address
    set num=0
    set tmp_str=%INSTALL_PATH%
    :label
    set /a num+=1
    set tmp_str=%tmp_str:~0,-1%
    if defined tmp_str goto :label
    if %num% GTR 256 (
        echo The total length of the path:%num%, exceeds 256 characters.
        goto :check_failed
    )

    call :check_path_legality "%INSTALL_PATH%" validity
    if [%validity%] equ [0] (
        echo "[%INSTALL_PATH%] is invalid, cannot contain Chinese character or space."
        goto :check_failed
    )

    for /f "tokens=2 delims=:" %%i in ('2^>nul fsutil volume diskfree %INSTALL_PATH%') do (set free_space=%%i)
    for /f "tokens=1 delims= " %%i in ("%free_space%") do (set free_space=%%i)
    set free_space=!free_space:,=!
    set free_space=!free_space:~0,-3!
    if not "!free_space!" == "-1" (
        set /a free_space=!free_space! / 1024
    )

    if not "!free_space!" == "-1" (
        if !free_space! LSS !FREE_SPACE_MIN! (
            call :Log "The space (%free_space%) of the installation directory is less than 5 GB."
            echo The space of the installation directory is less than 5 GB.
            goto :check_failed
        ) else (
            set "%~1=success"
            call :Log "The customer selection path is %INSTALL_PATH%."
            goto :EOF
        )
    ) else (
        call :Log "Failed to obtain the remaining memory of the installation address."
        goto :check_failed
    )

    :check_failed
        set "%~1=failed"
        goto :EOF

    goto :EOF

:check_activation_code
    set is_found=false
    set active_code_count=0
    if not defined ACTIVATION_CODE goto active_end

    :active_loop
        set tmp=!ACTIVATION_CODE:~%active_code_count%,1!

        if "%tmp%" == "" (
            goto :EOF
        )

        for %%i in (%COUNT_LIST%) do (
            if "%%i" == "%active_code_count%" (
                if not %tmp% == - (
                    echo "Please enter the correct activation code, Please check and try again"
                    pause
                    exit 1
                ) else (
                    set is_found=true
                    goto :active_break
                )
            ) else (
                for %%j in (%ACTIVE_CODE_LIST%) do (
                    if "%%j" == "%tmp%" (
                        set is_found=true
                        break
                    )
                )
            )
        )
        :active_break

        if %is_found% == true (
            set /a active_code_count+=1
            set /a is_found=false
            goto :active_loop
        ) else (
            echo "Please enter the correct activation code, Please check and try again"
            pause
            exit 1
        )

    :active_end
    goto :EOF

:check_length
    if %active_code_count% neq 36 (
        echo "Please enter the correct activation code, Please check and try again"
        pause
        exit 1
    )
    goto :EOF

:Log
    echo %date:~0,10% %time:~0,8% [%username%] "%~1" >> %LOG_FILE%
    goto :EOF

:write_path
    for,/f,"tokens=1,2,*",%%a,in,('reg query "HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Control\Session Manager\Environment" /v Path'),do,(
    set sys_path=%%c
    )
    set sys_path_value=!sys_path!
    set AGENT_PATH="%INSTALL_PYTHON_PATH%;%INSTALL_PYTHON_PATH%\Scripts;%INSTALL_PYTHON_PATH%\Lib\site-packages\pywin32_system32;%INSTALL_PYTHON_PATH%\Lib\site-packages\win32;"
    setx AGENT_PATH "%AGENT_PATH%" /m
    :loop
    for /f "tokens=1* delims=;" %%a in ("%sys_path_value%") do (
        if "%%a" == "%%AGENT_PATH%%" (
            set findflg=true
            break
        )
        set sys_path_value=%%b
    )
    if defined sys_path_value goto :loop

    if not "%findflg%" == "true" (
        wmic ENVIRONMENT where "name='path' and username='<system>'" set VariableValue="%sys_path%;%%AGENT_PATH%%"
    )

    set PATH_FILE=%INSTALL_PYTHON_PATH%\Lib\site-packages\agentassist.pth
    echo %INSTALL_PATH%\AgentAssist>>%PATH_FILE%
    echo %INSTALL_PATH%\AgentAssist\bin\assist>>%PATH_FILE%
    echo %INSTALL_PYTHON_PATH%>>%PATH_FILE%
    echo %INSTALL_PYTHON_PATH%\Scripts>>%PATH_FILE%
    echo %INSTALL_PYTHON_PATH%\Lib\site-packages\pywin32_system32>>%PATH_FILE%
    echo %INSTALL_PYTHON_PATH%\Lib\site-packages\win32>>%PATH_FILE%

    goto :EOF

:adjust_input_path
    if "%INSTALL_PATH:~-1%"  == "/" (
        set INSTALL_PATH=%INSTALL_PATH:~,-1%
        goto adjust_input_path
    ) else (
        if "%INSTALL_PATH:~-1%"  == "\" (
            set INSTALL_PATH=%INSTALL_PATH:~,-1%
            goto adjust_input_path
        )   else (
        set INSTALL_PATH=%INSTALL_PATH%\
        goto :EOF
        )
    )

:check_path_legality <path> <validity>
    Set "VbsFile=%~dp0conf\%~n0.vbs"
    (
        echo WScript.Echo(Is_Valid("%~1"^)^)
        echo Function Is_Valid(path^)
        echo    Dim RegularExpressionObject
        echo    Set RegularExpressionObject = New RegExp
        echo    With RegularExpressionObject
        echo        .Pattern = "[\u4e00-\u9fa5\s]+"
        echo        .IgnoreCase = False
        echo        If .Test(path^)= True then
        echo            Is_Valid = 0
        echo        Else
        echo            Is_Valid = 1
        echo        End if
        echo    End With
        echo End Function
    )>"%VbsFile%"
    @for /f "delims=" %%a in ('cscript //nologo "%VbsFile%"') do set "%2=%%a"
    Exit /B

