@echo off
REM ════════════════════════════════════════════════════════════════════
REM   CENTURY SANDESH AGENT - INSTALLER
REM   Century Mudra Tech Private Limited
REM   One-time run. Downloads Node, agent, dependencies.
REM   Registers persistent background task via Task Scheduler.
REM
REM   Deviations from build spec v2.0 (deliberate, see repo README):
REM     - better-sqlite3 pinned ^12 (spec's ^9 has no Node 22 prebuilt
REM       binary; would force a source compile + Visual Studio on the
REM       customer PC). ^12 ships a prebuilt binary — no compiler needed.
REM     - Task Scheduler runs run-agent.bat (a supervisor loop) instead of
REM       node directly, so the agent is relaunched after a self-update or
REM       crash. The login fallback only *starts* the primary task, so there
REM       is never a second agent instance fighting over port 4500.
REM ════════════════════════════════════════════════════════════════════

REM ── Force elevation (self-relaunches as admin if not already) ────────
net session >nul 2>&1
if %errorLevel% neq 0 (
    echo Requesting administrator privileges...
    powershell -Command "Start-Process '%~f0' -Verb RunAs"
    exit /b
)

setlocal enabledelayedexpansion
title Century Sandesh Agent Setup

REM ── Configuration ────────────────────────────────────────────────────
set "INSTALL_DIR=C:\SandeshAgent"
set "SERVER_URL=https://csagent.centurymudra.com"
set "AGENT_URL=%SERVER_URL%/agent.js"
set "RUNBAT_URL=%SERVER_URL%/run-agent.bat"
set "VERSION_URL=%SERVER_URL%/version.json"
set "NODE_MSI_URL=https://nodejs.org/dist/v22.12.0/node-v22.12.0-x64.msi"
set "TASK_NAME=SandeshAgent"
set "NODE_EXE=%ProgramFiles%\nodejs\node.exe"
set "AGENT_JS=%INSTALL_DIR%\agent.js"
set "RUN_BAT=%INSTALL_DIR%\run-agent.bat"
set "LOG_FILE=%INSTALL_DIR%\install.log"

REM ── /update flag — replace agent.js only, restart task ───────────────
if /i "%~1"=="/update" (
    echo Updating Sandesh Agent...
    schtasks /end /tn "%TASK_NAME%" >nul 2>&1
    powershell -Command "Invoke-WebRequest -Uri '%AGENT_URL%' -OutFile '%AGENT_JS%.new' -UseBasicParsing"
    if exist "%AGENT_JS%.new" (
        move /y "%AGENT_JS%.new" "%AGENT_JS%" >nul
        schtasks /run /tn "%TASK_NAME%" >nul 2>&1
        echo Update complete. Agent restarted.
    ) else (
        echo Update download failed. Agent unchanged.
    )
    pause
    exit /b 0
)

REM ── /reinstall flag — wipe config and state for fresh provisioning ────
if /i "%~1"=="/reinstall" (
    schtasks /end /tn "%TASK_NAME%" >nul 2>&1
    del /q "%INSTALL_DIR%\config.json" >nul 2>&1
    del /q "%INSTALL_DIR%\sandesh.db"  >nul 2>&1
    echo Reinstall: config and database wiped.
)

REM ── Create install dir early for logging ─────────────────────────────
if not exist "%INSTALL_DIR%"          mkdir "%INSTALL_DIR%"
if not exist "%INSTALL_DIR%\versions" mkdir "%INSTALL_DIR%\versions"

echo ══════════════════════════════════════════════ >  "%LOG_FILE%"
echo SANDESH AGENT INSTALL - %DATE% %TIME%         >> "%LOG_FILE%"
echo ══════════════════════════════════════════════ >> "%LOG_FILE%"

echo.
echo ════════════════════════════════════════════════════════════════════
echo    CENTURY SANDESH AGENT - SETUP
echo    Century Mudra Tech Private Limited
echo ════════════════════════════════════════════════════════════════════
echo    Install location : %INSTALL_DIR%
echo    Log file         : %LOG_FILE%
echo.

REM ── [1/7] Internet connectivity check ────────────────────────────────
echo [1/7] Checking internet...
powershell -Command "Invoke-WebRequest -Uri '%VERSION_URL%' -UseBasicParsing -TimeoutSec 10 | Out-Null" >nul 2>&1
if %errorLevel% neq 0 (
    echo [ERROR] Cannot reach update server. Check internet connection.
    echo [ERROR] Connectivity failed >> "%LOG_FILE%"
    pause
    exit /b 1
)
echo       Connected OK.

REM ── [2/7] Install Node.js if missing ─────────────────────────────────
echo.
echo [2/7] Checking Node.js...
where node >nul 2>&1
if %errorLevel% neq 0 (
    echo       Node.js not found. Downloading official installer...
    echo       This is a signed package from nodejs.org - safe to allow.
    powershell -Command "Invoke-WebRequest -Uri '%NODE_MSI_URL%' -OutFile '%TEMP%\node.msi' -UseBasicParsing" >> "%LOG_FILE%" 2>&1
    if not exist "%TEMP%\node.msi" (
        echo [ERROR] Node.js download failed.
        pause
        exit /b 1
    )
    echo       Installing Node.js silently...
    msiexec /i "%TEMP%\node.msi" /quiet /norestart >> "%LOG_FILE%" 2>&1
    timeout /t 20 /nobreak >nul
    del "%TEMP%\node.msi" >nul 2>&1
    set "PATH=%PATH%;%ProgramFiles%\nodejs"
)
if not exist "%NODE_EXE%" (
    echo [ERROR] Node.js install failed. See %LOG_FILE%.
    pause
    exit /b 1
)
"%NODE_EXE%" --version >> "%LOG_FILE%" 2>&1
echo       Node.js OK.

REM ── [3/7] Download agent.js and supervisor ───────────────────────────
echo.
echo [3/7] Downloading Sandesh Agent...
schtasks /end /tn "%TASK_NAME%" >nul 2>&1
powershell -Command "Invoke-WebRequest -Uri '%AGENT_URL%' -OutFile '%AGENT_JS%' -UseBasicParsing" >> "%LOG_FILE%" 2>&1
if not exist "%AGENT_JS%" (
    echo [ERROR] Failed to download agent.js.
    pause
    exit /b 1
)
for %%A in ("%AGENT_JS%") do (
    if %%~zA LSS 1000 (
        echo [ERROR] agent.js too small - likely an error page.
        type "%AGENT_JS%"
        pause
        exit /b 1
    )
)
powershell -Command "Invoke-WebRequest -Uri '%RUNBAT_URL%' -OutFile '%RUN_BAT%' -UseBasicParsing" >> "%LOG_FILE%" 2>&1
if not exist "%RUN_BAT%" (
    echo [ERROR] Failed to download run-agent.bat ^(supervisor^).
    pause
    exit /b 1
)
echo       Agent + supervisor downloaded.

REM ── [4/7] Write package.json and install npm dependencies ────────────
echo.
echo [4/7] Installing dependencies (2-3 minutes first time)...

(
echo {
echo   "name": "sandesh-agent",
echo   "version": "1.0.0",
echo   "private": true,
echo   "type": "module",
echo   "main": "agent.js",
echo   "dependencies": {
echo     "@whiskeysockets/baileys": "7.0.0-rc11",
echo     "better-sqlite3": "^12.2.0",
echo     "fastify": "^5.0.0",
echo     "libphonenumber-js": "^1.11.0",
echo     "qrcode-terminal": "^0.12.0",
echo     "mime-types": "^2.1.35"
echo   },
echo   "engines": { "node": ">=22.0.0" }
echo }
) > "%INSTALL_DIR%\package.json"

cd /d "%INSTALL_DIR%"
call npm install --omit=dev --no-audit --no-fund --loglevel=error >> "%LOG_FILE%" 2>&1
if %errorLevel% neq 0 (
    echo [ERROR] npm install failed. See %LOG_FILE%.
    pause
    exit /b 1
)
echo       Dependencies installed.

REM ── [5/7] Write default config.json ──────────────────────────────────
echo.
echo [5/7] Writing configuration...
if not exist "%INSTALL_DIR%\config.json" (
(
echo {
echo   "daily_cap": 100,
echo   "dedup_window_hours": 1,
echo   "min_delay_ms": 3000,
echo   "max_delay_ms": 8000,
echo   "port": 4500
echo }
) > "%INSTALL_DIR%\config.json"
)
echo 1.0.0 > "%INSTALL_DIR%\versions\current.txt"
echo       Config written.

REM ── [6/7] Register Task Scheduler jobs ───────────────────────────────
echo.
echo [6/7] Registering background service...
schtasks /delete /tn "%TASK_NAME%"      /f >nul 2>&1
schtasks /delete /tn "%TASK_NAME%_Boot" /f >nul 2>&1

REM Primary: supervisor loop on system boot as SYSTEM (relaunches agent.js
REM after self-update / crash). HIGHEST so it survives without a login.
schtasks /create /tn "%TASK_NAME%" ^
    /tr "\"%RUN_BAT%\"" ^
    /sc onstart /delay 0001:00 ^
    /ru "SYSTEM" /rl HIGHEST /f >> "%LOG_FILE%" 2>&1

REM Fallback: 2 min after any user login, just ENSURE the primary task is
REM running (never launches a second agent instance).
schtasks /create /tn "%TASK_NAME%_Boot" ^
    /tr "schtasks /run /tn \"%TASK_NAME%\"" ^
    /sc onlogon /delay 0002:00 ^
    /ru "SYSTEM" /rl HIGHEST /f >> "%LOG_FILE%" 2>&1

if %errorLevel% neq 0 (
    echo [ERROR] Failed to register scheduled task.
    pause
    exit /b 1
)
echo       Background service registered.

REM ── Lock config.json to SYSTEM and Administrators only ───────────────
icacls "%INSTALL_DIR%\config.json" /inheritance:r /grant:r SYSTEM:F "BUILTIN\Administrators:F" >> "%LOG_FILE%" 2>&1
echo       config.json locked to Admins.

REM ── [7/7] First run — show QR in console for WhatsApp pairing ─────────
echo.
echo ════════════════════════════════════════════════════════════════════
echo    Setup complete. Starting WhatsApp pairing...
echo ════════════════════════════════════════════════════════════════════
echo.
echo    A QR code will appear below.
echo    Open WhatsApp on your phone:
echo      Android : Menu (3 dots) - Linked Devices - Link a Device
echo      iPhone  : Settings - Linked Devices - Link a Device
echo    Scan the QR. Once paired this agent runs automatically.
echo.
echo    Press any key when ready...
pause >nul

"%NODE_EXE%" "%AGENT_JS%" --firstrun

echo.
echo ════════════════════════════════════════════════════════════════════
echo    ALL DONE.
echo    Sandesh Agent runs automatically on every PC start.
echo    Open SandeshAgent.xlsm from %INSTALL_DIR% to send messages.
echo    Support: support@centurymudra.com
echo ════════════════════════════════════════════════════════════════════
echo.
pause
exit /b 0
