@echo off
setlocal

REM Define variables
set "serviceName=QuickpassServerAgent"
set "downloadURL=https://storage.googleapis.com/qp-installer/production/Quickpass-Agent-Setup.exe"
set "fileName=Quickpass-Agent-Setup.exe"
set "outputPath=C:\QPInstall"  REM Modify this path as needed
set "installToken=InstallToken"
set "agentID=CustomerAgentID"
set "regionID=NA"
set "restartOption=/NORESTART"
set "msaOption=MSA=1"

REM Ensure the path ends with a backslash
if not "%outputPath:~-1%"=="\" set "outputPath=%outputPath%\"

REM Full path to the output file
set "fullOutputPath=%outputPath%%fileName%"
set "logFile=%outputPath%QPInst.log"

REM Check if the service exists
sc query %serviceName% >nul 2>&1
if %errorlevel% equ 0 (
    echo The service "%serviceName%" already exists. No installation needed. > "%logFile%"
    exit /b 0
)

REM Create the download directory if it doesn't exist
if not exist "%outputPath%" (
    mkdir "%outputPath%"
)

REM Log the start of the process
echo Starting Quickpass Agent installation... >> "%logFile%"
echo %date% %time% >> "%logFile%"

REM Download the file using curl
echo Downloading Quickpass Agent... >> "%logFile%"
curl -o "%fullOutputPath%" "%downloadURL%" >> "%logFile%" 2>&1
if %errorlevel% neq 0 (
    echo Failed to download the file. >> "%logFile%"
    exit /b 1
)

REM Run the installer
echo Installing Quickpass Agent... >> "%logFile%"
"%fullOutputPath%" /quiet %restartOption% INSTALLTOKEN="%installToken%" CUSTOMERID="%agentID%" REGION="%regionID%" %msaOption% >> "%logFile%" 2>&1
if %errorlevel% neq 0 (
    echo Installation failed. >> "%logFile%"
    exit /b 1
)

echo Installation completed successfully. >> "%logFile%"
echo %date% %time% >> "%logFile%"
endlocal
exit /b 0