@echo off
setlocal enabledelayedexpansion
title Space Net node setup
set "SRC=https://oracle2.spaceai.net"
set "DIR=%LOCALAPPDATA%\SpaceNet"
set "LOG=%TEMP%\spacenet-install.log"
echo === Space Net node setup ===
echo Source: %SRC%
echo Install to: %DIR%
echo.

where node >nul 2>nul
if %errorlevel%==0 goto haveNode
echo Node.js is required and was not found.
set /p ANS="Download and install Node.js LTS from nodejs.org now? [Y/N]: "
if /i not "%ANS%"=="Y" (echo Install Node.js from https://nodejs.org then run this again. & pause & exit /b 1)
echo Downloading Node.js...
curl -L -# -o "%TEMP%\node-setup.msi" https://nodejs.org/dist/v22.14.0/node-v22.14.0-x64.msi
echo Installing (Windows may ask for permission)...
msiexec /i "%TEMP%\node-setup.msi" /passive /norestart
set "PATH=%ProgramFiles%\nodejs;%PATH%"
where node >nul 2>nul || (echo Node.js install did not complete. & pause & exit /b 1)
:haveNode
for /f "delims=" %%v in ('node -v') do echo Node.js %%v

if not exist "%DIR%" mkdir "%DIR%"
if not exist "%DIR%\storage" mkdir "%DIR%\storage"
echo Downloading the node software...
for %%f in (serve.js sos-desktop.html satellite.min.js sos.ico) do (
  curl -fsSL "%SRC%/dl/%%f" -o "%DIR%\%%f" && echo   %%f
)

rem a shortcut so it can be started again without this installer
> "%DIR%\Start Space Net.bat" echo @echo off
>> "%DIR%\Start Space Net.bat" echo cd /d "%DIR%"
>> "%DIR%\Start Space Net.bat" echo start "" http://localhost:8777/
>> "%DIR%\Start Space Net.bat" echo node serve.js

echo.
echo Starting the node...
cd /d "%DIR%"
start "Space Net node" /min cmd /c "node serve.js >> "%LOG%" 2>&1"
rem give it a moment to bind the port before the browser asks for it
ping -n 6 127.0.0.1 >nul
start "" http://localhost:8777/
echo.
echo Space Net is running at http://localhost:8777/
echo Start it again later with: %DIR%\Start Space Net.bat
echo Log: %LOG%
echo.
pause