@echo off
setlocal EnableExtensions

rem Silent Task Scheduler installer for IT deployments.
rem Optional environment variables:
rem   TASK_NAME=Atalya Chrono Backup Daily
rem   TASK_TIME=02:00
rem   CLI_EXE=C:\Path\To\Atalya.Backup.Cli.exe

set "DEFAULT_TASK_NAME=Atalya Chrono Backup Daily"
set "DEFAULT_TASK_TIME=02:00"

if "%TASK_NAME%"=="" set "TASK_NAME=%DEFAULT_TASK_NAME%"
if "%TASK_TIME%"=="" set "TASK_TIME=%DEFAULT_TASK_TIME%"

if "%CLI_EXE%"=="" (
    if exist "%~dp0Atalya.Backup.Cli.exe" set "CLI_EXE=%~dp0Atalya.Backup.Cli.exe"
)

if "%CLI_EXE%"=="" (
    if exist "%LOCALAPPDATA%\Atalya.Chrono.Backup\current\Atalya.Backup.Cli.exe" set "CLI_EXE=%LOCALAPPDATA%\Atalya.Chrono.Backup\current\Atalya.Backup.Cli.exe"
)

if "%CLI_EXE%"=="" (
    echo Atalya.Backup.Cli.exe could not be found.
    echo Set CLI_EXE before running this script.
    exit /b 2
)

if not exist "%CLI_EXE%" (
    echo CLI executable does not exist:
    echo   %CLI_EXE%
    exit /b 2
)

if not exist "%ProgramData%\Atalya\Backup" mkdir "%ProgramData%\Atalya\Backup"

set "TASK_COMMAND=\"%CLI_EXE%\" --source Scheduled"

schtasks /Create /TN "%TASK_NAME%" /TR "%TASK_COMMAND%" /SC DAILY /ST "%TASK_TIME%" /RL HIGHEST /F
if not "%errorlevel%"=="0" (
    echo Scheduled task could not be created. Run as Administrator or provide required rights.
    exit /b 1
)

echo Scheduled task created or updated.
echo Task name: %TASK_NAME%
echo Task time: %TASK_TIME%
echo CLI: %CLI_EXE%
exit /b 0
