@echo off
cd /D "%~dp0"
echo This script installs the Beszel agent for Windows.
echo If not yet installed, NSSM will be installed via Winget.
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
)

if !%1==! goto help
if !%2==! goto help

set BESZELKEYPREFIX=%1
set BESZELKEY=%2
call env.cmd

where nssm.exe >nul 2>&1
if %errorlevel% NEQ 0 goto installnssm
goto proceed

:installnssm
echo Downloading NSSM
curl.exe --output "%TEMP%\nssm-2.24.zip" --url https://nssm.cc/release/nssm-2.24.zip >nul 2>&1
echo Extracting ZIP file
tar.exe -xf %TEMP%\nssm-2.24.zip >nul 2>&1
echo Copying nssm.exe to %DESTINATIONDIR%
if %PROCESSOR_ARCHITECTURE%==AMD64 (
	copy .\nssm-2.24\win64\nssm.exe "%DESTINATIONDIR%\" >nul 2>&1
) else (
	copy .\nssm-2.24\win32\nssm.exe "%DESTINATIONDIR%\" >nul 2>&1
)
set NSSMEXE="%DESTINATIONDIR%\nssm.exe"
echo Deleting temporary files and directories
del "%TEMP%\nssm-2.24.zip" >nul 2>&1
rd /s/q .\nssm-2.24 >nul 2>&1

:proceed
echo Creating directory %DESTINATIONDIR%
md "%DESTINATIONDIR%" >nul 2>&1

echo Copying agent.exe to %DESTINATIONDIR%
copy .\agent.exe "%DESTINATIONDIR%\" >nul 2>&1

echo Adding firewall rule
netsh advfirewall firewall add rule name="%SERVICENAME%" dir=in action=allow program="%AGENTEXE%" enable=yes >nul 2>&1

echo Installing service %SERVICENAME%
%NSSMEXE% install %SERVICENAME% "%AGENTEXE%" >nul 2>&1
if %errorlevel% NEQ 0 (
	echo Failed to install the service.
	goto end
)

echo Setting environment for %SERVICENAME%
%NSSMEXE% set %SERVICENAME% AppEnvironmentExtra "KEY=%BESZELKEYPREFIX% %BESZELKEY%" >nul 2>&1
if %errorlevel% NEQ 0 (
	echo Failed to set the service environment.
	goto end
)

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

echo Dumping service state
%NSSMEXE% dump %SERVICENAME%
goto end

:help
echo You have to provide a Beszel ssh key, e.g. 'install-beszel-service.cmd ssh-ed25519 AAAAC3L3lIpn94iu2TIpdmneXsEC1TDvrg4HCNoM1aiC683WMZfGOVoatrJSkysaQB9K
echo The key must not be enclosed in "" or '', just copy and paste it as it is.

:end