@echo off
REM Restore Command Nexus after a failed in-app update. Campaigns are not touched.
setlocal EnableExtensions
title AETHER Recover
echo.
echo This closes stuck Command Nexus processes and restores the previous
echo build if the current one is broken. Campaigns stay on this PC.
echo.
pause
echo.

if not defined LOCALAPPDATA set "LOCALAPPDATA=%USERPROFILE%\AppData\Local"
set "DEST=%LOCALAPPDATA%\AETHER"
set "APP=%DEST%\app"
set "PREV=%DEST%\updates\app.prev"
set "PREV2=%DEST%\app.prev"
set "LOG=%DEST%\logs\recover.log"
if not exist "%DEST%\logs" mkdir "%DEST%\logs"
echo %DATE% %TIME% recover start>> "%LOG%"

echo Closing stuck launcher processes...
taskkill /IM AetherSplashHost.exe /F >nul 2>&1
powershell.exe -NoProfile -ExecutionPolicy Bypass -Command "Get-CimInstance Win32_Process | Where-Object { $_.CommandLine -and ($_.CommandLine -match 'aether_desktop_splash') } | ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue }"

set "NEED="
if not exist "%APP%\VERSION.json" set "NEED=1"
if not exist "%APP%\scripts\aether_desktop_splash.py" set "NEED=1"
if not exist "%APP%\splash\launcher.html" set "NEED=1"

if defined NEED (
  echo Current install looks incomplete. Restoring the previous build...
  echo %DATE% %TIME% restore needed>> "%LOG%"
  if exist "%PREV%\VERSION.json" (
    if exist "%APP%" (
      if exist "%APP%.broken" rmdir /s /q "%APP%.broken"
      move /y "%APP%" "%APP%.broken" >> "%LOG%" 2>&1
    )
    move /y "%PREV%" "%APP%" >> "%LOG%" 2>&1
    echo Restored from updates\app.prev
  ) else if exist "%PREV2%\VERSION.json" (
    if exist "%APP%" (
      if exist "%APP%.broken" rmdir /s /q "%APP%.broken"
      move /y "%APP%" "%APP%.broken" >> "%LOG%" 2>&1
    )
    move /y "%PREV2%" "%APP%" >> "%LOG%" 2>&1
    echo Restored from app.prev
  ) else (
    echo No previous build was found.
    echo Download the Windows pack from https://aethercommandnexus.com
    echo extract it, and run Install-AETHER.cmd
    echo.
    pause
    exit /b 1
  )
) else (
  echo Current install files look present.
)

if not exist "%APP%\VERSION.json" (
  echo Still missing app\VERSION.json.
  echo Download the Windows pack from https://aethercommandnexus.com
  echo.
  pause
  exit /b 1
)

set "LAUNCH=%DEST%\start-aether-desktop.cmd"
if not exist "%LAUNCH%" set "LAUNCH=%APP%\start-aether-desktop.cmd"
echo Starting Command Nexus...
if exist "%LAUNCH%" (
  start "" "%LAUNCH%"
) else (
  echo Could not find start-aether-desktop.cmd
  echo Download the Windows pack and run Install-AETHER.cmd
  pause
  exit /b 1
)
echo.
echo If the launcher still does not appear, download the Windows pack
echo from https://aethercommandnexus.com and run Install-AETHER.cmd
echo.
pause
exit /b 0
