@echo off
setlocal
cd /D "%~dp0"
echo This script updates the Beszel agent to the latest version from the Github repository
echo.

echo Checking adminstrative rights
rem from https://stackoverflow.com/questions/7985755/how-to-detect-if-cmd-is-running-as-administrator-has-elevated-privileges
net session >nul 2>&1
if %errorlevel% equ 0 (
	echo Administrative rights check OK
) else (
	echo You are NOT Administrator. Start the script from an administrative cmd.exe shell...
	goto end
)

call env.cmd

where winget.exe >nul 2>&1
if %errorlevel% NEQ 0 (
	echo Winget not found, install Winget or use a compatible OS: Win 10 Client OS or later
	goto end
) else (
	echo Winget executable found
)

where go.exe >nul 2>&1
if %errorlevel% NEQ 0 (
	echo Installing Go with Winget
	winget install GoLang.Go
) else (
	echo Go executable found
)

where git.exe >nul 2>&1
if %errorlevel% NEQ 0 (
	echo Installing Git with Winget
	winget install Git.Git
) else (
	echo Git executable found
)

if exist .\beszel (
	echo Subdirectory beszel already exists, it has to be deleted.
	echo   - Hit Crtl+c to exit if you don't want the directory to be deleted.
	echo   - Hit any other key to continue
	pause  >nul 2>&1
	echo Deleting beszel subdirectory
	rd /q/s .\beszel >nul 2>&1
)

:proceed
echo Cloning Beszel repository from Github
git clone https://github.com/henrygd/beszel.git >nul 2>&1
if %errorlevel% NEQ 0 (
	echo Cloning repository failed.
	goto end
)

cd .\beszel\beszel\cmd\agent

echo Building agent
set GOOS=windows
set GOARCH=amd64
set CGO_ENABLED=0
go build -ldflags "-w -s" . >nul 2>&1
if %errorlevel% NEQ 0 (
	echo Something went wrong
	goto end
) else (
	echo Build successful
)

cd /D "%~dp0"

echo Stopping Beszel agent service
net stop %SERVICENAME% >nul 2>&1
if %errorlevel% NEQ 0 (
	echo Failed to stop Beszel agent service
	goto end
)

echo Copying new agent
copy .\beszel\beszel\cmd\agent\agent.exe %AGENTEXE% >nul 2>&1
if %errorlevel% NEQ 0 (
	echo Failed to copy agent.exe
)

echo Starting Beszel agent service
net start %SERVICENAME% >nul 2>&1
if %errorlevel% NEQ 0 (
	echo Failed to start Beszel agent service
	goto end
)

:end
endlocal