@echo off
setlocal EnableDelayedExpansion
title URVault -- Reset Admin Account
color 0C

:: ── Admin check ───────────────────────────────────────────────────────────────
net session >nul 2>&1
if %errorLevel% neq 0 (
    echo.
    echo  Requesting administrator access...
    powershell -NoProfile -ExecutionPolicy Bypass -Command "Start-Process -FilePath cmd.exe -ArgumentList '/k \"\"%~f0\"\"' -Verb RunAs -WindowStyle Normal"
    exit /b
)

cd /d "%~dp0"

echo.
echo  ============================================================
echo    URVault -- Reset Admin Account
echo  ============================================================
echo.
echo  This will:
echo    1. Stop the URVault server service
echo    2. Delete the existing admin account
echo    3. Reset the setup wizard so you can create a new admin
echo    4. Restart the server
echo.
echo  Your backup files and device pairings are NOT affected.
echo.
set /p "CONFIRM=  Type YES to confirm: "
set "CONFIRM=!CONFIRM: =!"
if /i not "!CONFIRM!"=="YES" (
    echo.
    echo  Cancelled.
    pause & exit /b 0
)
echo.

:: ── Read .env ─────────────────────────────────────────────────────────────────
if not exist "%~dp0.env" (
    echo  ERROR: .env not found in %~dp0
    echo  Run the installer first, then try again.
    pause & exit /b 1
)

for /f "tokens=1,2 delims==" %%k in (%~dp0.env) do (
    if "%%k"=="DB_USER"     set "DB_USER=%%l"
    if "%%k"=="DB_PASSWORD" set "DB_PASSWORD=%%l"
    if "%%k"=="DB_NAME"     set "DB_NAME=%%l"
    if "%%k"=="DB_HOST"     set "DB_HOST=%%l"
    if "%%k"=="DB_PORT"     set "DB_PORT=%%l"
    if "%%k"=="STORAGE_PATH" set "STORAGE_PATH=%%l"
)

if not defined DB_USER     set "DB_USER=urvault"
if not defined DB_NAME     set "DB_NAME=urvault"
if not defined DB_HOST     set "DB_HOST=localhost"
if not defined DB_PORT     set "DB_PORT=3306"

:: ── Stop service ──────────────────────────────────────────────────────────────
echo  Stopping URVault service...
nssm stop URVaultServer >nul 2>&1
powershell -NoProfile -Command "try{Stop-Service 'URVaultServer' -Force -EA SilentlyContinue}catch{}" >nul 2>&1
timeout /t 3 /nobreak >nul
echo  Done.
echo.

:: ── Ensure MySQL is reachable ─────────────────────────────────────────────────
powershell -NoProfile -Command "try{$t=New-Object Net.Sockets.TcpClient;$t.Connect('127.0.0.1',3306);$t.Close();exit 0}catch{exit 1}" >nul 2>&1
if !errorLevel! neq 0 (
    echo  ERROR: MySQL is not responding on port 3306.
    echo  Start the MySQL service ^(services.msc^) and try again.
    pause & exit /b 1
)

:: ── Scan MySQL bin paths so mysql.exe is in PATH ──────────────────────────────
for %%v in (9.2 9.1 9.0 8.4 8.3 8.2 8.1 8.0 5.7) do (
    if not defined MYSQL_PATH_ADDED (
        if exist "C:\Program Files\MySQL\MySQL Server %%v\bin\mysql.exe" (
            set "PATH=!PATH!;C:\Program Files\MySQL\MySQL Server %%v\bin"
            set "MYSQL_PATH_ADDED=1"
        )
    )
)

mysql --version >nul 2>&1
if !errorLevel! neq 0 (
    echo  ERROR: mysql.exe not found. Add MySQL bin to PATH and try again.
    pause & exit /b 1
)

:: ── Clear admin_users table ───────────────────────────────────────────────────
echo  Clearing admin account from database...
mysql -h !DB_HOST! -P !DB_PORT! -u "!DB_USER!" -p"!DB_PASSWORD!" !DB_NAME! -e "TRUNCATE TABLE admin_users;" >nul 2>&1
if !errorLevel! neq 0 (
    echo.
    echo  WARNING: Could not clear admin_users with the urvault DB user.
    echo  Trying root credentials...
    echo.
    set /p "ROOT_PW=  MySQL root password: "
    mysql -h !DB_HOST! -P !DB_PORT! -u root -p"!ROOT_PW!" !DB_NAME! -e "TRUNCATE TABLE admin_users;" 2>&1
    if !errorLevel! neq 0 (
        echo.
        echo  ERROR: Could not clear admin_users table.
        echo  Connect manually: mysql -u root -p !DB_NAME!
        echo  Then run: TRUNCATE TABLE admin_users;
        pause & exit /b 1
    )
)
echo  Admin account cleared.
echo.

:: ── Reset setup-config.json ───────────────────────────────────────────────────
echo  Resetting setup wizard state...
if defined STORAGE_PATH (
    set "CFG_PATH=!STORAGE_PATH!\setup-config.json"
) else (
    set "CFG_PATH=C:\ProgramData\URVault\backups\setup-config.json"
)

if exist "!CFG_PATH!" (
    :: Use Node.js to safely update the JSON
    node -e "try{const fs=require('fs'),p='!CFG_PATH!'.replace(/\\\\/g,'\\\\\\\\');let c=JSON.parse(fs.readFileSync(p,'utf8'));c.adminConfigured=false;c.setupCompleted=false;fs.writeFileSync(p,JSON.stringify(c,null,2));console.log('  setup-config.json updated');}catch(e){console.log('  WARNING: could not update setup-config.json: '+e.message);}"
) else (
    echo  setup-config.json not found at !CFG_PATH! -- will be recreated on next start.
)
echo.

:: ── Restart service ───────────────────────────────────────────────────────────
echo  Starting URVault service...
nssm start URVaultServer >nul 2>&1
if !errorLevel! neq 0 (
    powershell -NoProfile -Command "try{Start-Service 'URVaultServer' -EA SilentlyContinue}catch{}" >nul 2>&1
)

:: Wait for server to respond
set "SRV_READY=0"
for /L %%w in (1,1,6) do (
    if "!SRV_READY!"=="0" (
        timeout /t 3 /nobreak >nul
        powershell -NoProfile -Command "try{$t=New-Object Net.Sockets.TcpClient;$t.Connect('127.0.0.1',5173);$t.Close();exit 0}catch{exit 1}" >nul 2>&1
        if !errorLevel! equ 0 set "SRV_READY=1"
    )
)

echo.
echo  ============================================================
echo    Admin Reset Complete
echo  ============================================================
echo.
if "!SRV_READY!"=="1" (
    echo    Server is running. Open your browser to create a new admin:
) else (
    echo    Server may still be starting. Open your browser to create a new admin:
)
echo.
echo      http://localhost:5173
echo.
echo    Complete the setup wizard to set your new admin password.
echo.
pause
