@echo off
REM SPDX-License-Identifier: GPL-3.0-or-later
REM ──────────────────────────────────────────────────────────────────────────
REM Private Archive — Meta-bundle Installer (Windows)
REM
REM Installs the backend daemon, CLI, and desktop app, then registers the
REM backend as a Windows Service or Scheduled Task.
REM
REM Usage:
REM   install.bat              user-level (no admin)
REM   install.bat --system     system service (requires Run as Administrator)
REM   install.bat --no-service skip service registration
REM ──────────────────────────────────────────────────────────────────────────
setlocal

set "SCRIPT_DIR=%~dp0"
set "BIN_DIR=%LOCALAPPDATA%\PrivateArchive\bin"
set "SYSTEM_INSTALL="
set "INSTALL_SERVICE=1"

:parse_args
if "%~1"=="" goto :done_args
if /i "%~1"=="--system" (
    set "SYSTEM_INSTALL=1"
    set "BIN_DIR=%ProgramFiles%\PrivateArchive\bin"
)
if /i "%~1"=="--no-service" set "INSTALL_SERVICE="
if /i "%~1"=="--help" goto :show_help
if /i "%~1"=="-h" goto :show_help
shift
goto :parse_args

:show_help
echo Usage: install.bat [--system] [--no-service]
echo.
echo   --system       Install as a Windows Service (requires Administrator)
echo   --no-service   Copy binaries only, skip service registration
exit /b 0

:done_args

echo Private Archive Installer
echo =========================
echo Install directory: %BIN_DIR%
echo.

if not exist "%BIN_DIR%" mkdir "%BIN_DIR%"

REM Copy CLI + backend binaries
for %%f in ("%SCRIPT_DIR%bin\*") do (
    copy /y "%%f" "%BIN_DIR%\" >nul
    echo   Installed %BIN_DIR%\%%~nxf
)

REM Copy desktop bundle (Tauri MSI is normally run separately, but if the
REM raw .exe is shipped here we install it alongside the CLI binaries).
if exist "%SCRIPT_DIR%desktop\PrivateBackup.exe" (
    copy /y "%SCRIPT_DIR%desktop\PrivateBackup.exe" "%BIN_DIR%\" >nul
    echo   Installed desktop app
)

REM Register backend service
set "BACKEND=%BIN_DIR%\privatebackup-backend.exe"
if not defined INSTALL_SERVICE goto :skip_service
if not exist "%BACKEND%" (
    echo Warning: privatebackup-backend.exe not found, skipping service registration.
    goto :skip_service
)

echo.
echo Registering backend service...
if defined SYSTEM_INSTALL (
    "%BACKEND%" service install --system
) else (
    "%BACKEND%" service install
)
if errorlevel 1 (
    echo   Warning: service registration failed.
    echo   Run '%BACKEND% service install' manually.
)

:skip_service

REM Add to user PATH if user-level install
if not defined SYSTEM_INSTALL (
    echo.
    for /f "tokens=2*" %%a in ('reg query "HKCU\Environment" /v Path 2^>nul') do set "CURRENT_PATH=%%b"
    echo %CURRENT_PATH% | find /i "%BIN_DIR%" >nul 2>&1
    if errorlevel 1 (
        setx PATH "%CURRENT_PATH%;%BIN_DIR%" >nul 2>&1
        echo   Added %BIN_DIR% to user PATH. Restart your terminal.
    )
)

echo.
echo Installation complete.
echo.
echo Verify with:
echo   privatebackup-backend service status
echo   privatebackup --help

endlocal
