@echo off
title HydraOPS Installer v15.0.0
color 0B
echo.
echo   ==================================================
echo        HydraOPS - Full Installation
echo        Version 15.0.0
echo   ==================================================
echo.

set INSTALL_DIR=%LocalAppData%\HydraOPS
set STARTUP_DIR=%AppData%\Microsoft\Windows\Start Menu\Programs\Startup
set SCRIPT_DIR=%~dp0
set SERVER_URL=https://ops.onyx.ps

:: ============================================================
:: PHASE 1: Kill ALL running processes
:: ============================================================
echo   [1/7] Stopping all running instances...
taskkill /F /IM HydraOPS.exe >nul 2>&1
taskkill /F /IM HydraKeeper.exe >nul 2>&1
timeout /t 2 /nobreak >nul
echo         Done.

:: ============================================================
:: PHASE 2: Deep clean using Everything SDK
:: ============================================================
echo   [2/7] Deep cleaning old installations...

if exist "%SCRIPT_DIR%es.exe" (
    echo         Scanning all drives with Everything...

    for /f "delims=" %%F in ('"%SCRIPT_DIR%es.exe" -name HydraOPS.exe -name HydraOPS_old.exe -name HydraOPS.exe.bak -name HydraOPS_update.exe 2^>nul') do (
        if /i not "%%F"=="%SCRIPT_DIR%HydraOPS.exe" (
            echo         Deleting: %%F
            del /f /q "%%F" >nul 2>&1
        )
    )

    for /f "delims=" %%F in ('"%SCRIPT_DIR%es.exe" -name HydraKeeper.exe 2^>nul') do (
        echo         Deleting: %%F
        del /f /q "%%F" >nul 2>&1
    )

    for /f "delims=" %%F in ('"%SCRIPT_DIR%es.exe" -name keeper.bat -name keeper.log -name _update.cmd -name "HydraOPS.exe.update*" 2^>nul') do (
        echo         Deleting: %%F
        del /f /q "%%F" >nul 2>&1
    )

    for /f "delims=" %%F in ('"%SCRIPT_DIR%es.exe" -path HydraOPS -name token.txt 2^>nul') do (
        echo         Deleting: %%F
        del /f /q "%%F" >nul 2>&1
    )

    echo         Everything scan complete.
) else (
    echo         Everything not found — using manual cleanup...
)

:: Manual cleanup fallback
rmdir /s /q C:\HydraOPS >nul 2>&1
rmdir /s /q D:\HydraOPS >nul 2>&1
rmdir /s /q C:\ProgramData\HydraOPS >nul 2>&1
if exist "%INSTALL_DIR%" (
    del /f /q "%INSTALL_DIR%\HydraKeeper.exe" >nul 2>&1
    del /f /q "%INSTALL_DIR%\HydraOPS.exe.bak" >nul 2>&1
    del /f /q "%INSTALL_DIR%\HydraOPS_old.exe" >nul 2>&1
    del /f /q "%INSTALL_DIR%\keeper.bat" >nul 2>&1
    del /f /q "%INSTALL_DIR%\_update.cmd" >nul 2>&1
)
echo         Done.

:: ============================================================
:: PHASE 3: Clean services, tasks, shortcuts, registry
:: ============================================================
echo   [3/7] Removing old services and tasks...
schtasks /Delete /TN "HydraOPS-Agent" /F >nul 2>&1
schtasks /Delete /TN "HydraOPS-Keeper" /F >nul 2>&1
schtasks /Delete /TN "HydraOPS" /F >nul 2>&1
sc stop HydraOPS-Agent >nul 2>&1
sc delete HydraOPS-Agent >nul 2>&1
reg delete "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\HydraOPS" /f >nul 2>&1
del "%STARTUP_DIR%\HydraOPS.lnk" >nul 2>&1
del "%STARTUP_DIR%\HydraKeeper.lnk" >nul 2>&1
del C:\Users\Public\Desktop\HydraOPS.lnk >nul 2>&1
echo         Done.

:: ============================================================
:: PHASE 4: Install new version
:: ============================================================
echo   [4/7] Installing HydraOPS v15.0.0...
if not exist "%INSTALL_DIR%" mkdir "%INSTALL_DIR%"
copy /y "%SCRIPT_DIR%HydraOPS.exe" "%INSTALL_DIR%\HydraOPS.exe" >nul
if exist "%SCRIPT_DIR%Microsoft.Data.SqlClient.SNI.dll" copy /y "%SCRIPT_DIR%Microsoft.Data.SqlClient.SNI.dll" "%INSTALL_DIR%\Microsoft.Data.SqlClient.SNI.dll" >nul
if exist "%SCRIPT_DIR%es.exe" copy /y "%SCRIPT_DIR%es.exe" "%INSTALL_DIR%\es.exe" >nul
echo         Installed to: %INSTALL_DIR%

:: ============================================================
:: PHASE 5: Register with server (get token)
:: ============================================================
echo   [5/7] Registering with server...

:: Get company name
set /p COMPANY_NAME="        Enter company name: "
if "%COMPANY_NAME%"=="" set COMPANY_NAME=Client

:: Get machine fingerprint
for /f "tokens=2 delims==" %%A in ('wmic bios get serialnumber /format:list 2^>nul ^| find "="') do set BIOS_SN=%%A
for /f "tokens=2 delims==" %%A in ('wmic baseboard get serialnumber /format:list 2^>nul ^| find "="') do set BOARD_SN=%%A
set MACHINE_ID=%COMPUTERNAME%-%BIOS_SN%-%BOARD_SN%

:: Call /register API
powershell -Command ^
  "$body = @{ company_name='%COMPANY_NAME%'; machine_id='%MACHINE_ID%' } | ConvertTo-Json; " ^
  "$r = Invoke-RestMethod -Uri '%SERVER_URL%/register' -Method POST -ContentType 'application/json' -Body $body; " ^
  "if ($r.success) { " ^
  "  if ($r.agent_token -eq 'reuse') { " ^
  "    Write-Host '        Machine already registered — keeping existing config'; " ^
  "    Write-Host '        Agent ID:' $r.agent_id; " ^
  "  } else { " ^
  "    $cfg = @{ AgentToken=$r.agent_token; AgentId=$r.agent_id; ClientId=$r.client_id; ClientName='%COMPANY_NAME%'; AppUrl='%SERVER_URL%/app'; MachineId='%MACHINE_ID%' } | ConvertTo-Json; " ^
  "    $cfg | Out-File -Encoding utf8 '%INSTALL_DIR%\hydraops.json'; " ^
  "    Write-Host '        Registered successfully as:' $r.client_id; " ^
  "  } " ^
  "  Write-Host '        App URL: %SERVER_URL%/app'; " ^
  "} else { " ^
  "  Write-Host '        Registration failed:' $r.error; " ^
  "}"

:: If no config exists, agent will show setup wizard
if not exist "%INSTALL_DIR%\hydraops.json" (
    echo         WARNING: No config found. Agent will show setup wizard.
)
echo         Done.

:: ============================================================
:: PHASE 6: Create shortcuts
:: ============================================================
echo   [6/7] Creating shortcuts...

powershell -Command "$ws = New-Object -ComObject WScript.Shell; $s = $ws.CreateShortcut('%STARTUP_DIR%\HydraOPS.lnk'); $s.TargetPath = '%INSTALL_DIR%\HydraOPS.exe'; $s.Arguments = '--service'; $s.WorkingDirectory = '%INSTALL_DIR%'; $s.Description = 'HydraOPS Agent'; $s.Save()" >nul 2>&1

powershell -Command "$ws = New-Object -ComObject WScript.Shell; $s = $ws.CreateShortcut([Environment]::GetFolderPath('Desktop') + '\HydraOPS.lnk'); $s.TargetPath = '%INSTALL_DIR%\HydraOPS.exe'; $s.WorkingDirectory = '%INSTALL_DIR%'; $s.Description = 'HydraOPS Agent'; $s.Save()" >nul 2>&1
echo         Done.

:: ============================================================
:: PHASE 7: Launch
:: ============================================================
echo   [7/7] Starting HydraOPS...
start "" "%INSTALL_DIR%\HydraOPS.exe"
echo         Done.

echo.
echo   ==================================================
echo        Installation Complete!
echo.
echo   Version  : 15.0.0
echo   Location : %INSTALL_DIR%
echo   Settings : http://127.0.0.1:53230
echo   ==================================================
echo.
echo   Press any key to close...
pause >nul
