@echo off
REM ==========================================================================
REM  OpenDesk - one-click install + start for Windows 10/11 (no admin needed)
REM
REM  Double-click this file. It will:
REM    1. download uv (a tiny Python manager) into %LOCALAPPDATA%\OpenDesk
REM    2. let uv install a private Python 3.12 + the OpenDesk libraries
REM    3. get host_agent.py (from the folder next to this file, or the server)
REM    4. create Desktop + Start Menu shortcuts and an uninstaller
REM    5. start OpenDesk (window shows your ID and password)
REM  Running it again updates OpenDesk.
REM ==========================================================================
setlocal EnableExtensions
title OpenDesk Setup

REM The server fills these in when you download from it; otherwise you are asked.
set "SERVER=wss://samir-1.tail6f4325.ts.net/ws"
set "BASE=https://samir-1.tail6f4325.ts.net"

set "APP=%LOCALAPPDATA%\OpenDesk"
set "SRC=%~dp0"
set "UV=%APP%\uv.exe"
set "PY=%APP%\venv\Scripts\python.exe"
set "PYW=%APP%\venv\Scripts\pythonw.exe"
set "UV_PYTHON_INSTALL_DIR=%APP%\python"
set "UV_CACHE_DIR=%APP%\cache"
set "KILL=Get-CimInstance Win32_Process -Filter \"Name='pythonw.exe'\" | Where-Object { $_.CommandLine -like '*OpenDesk*host_agent.py*' } | ForEach-Object { Stop-Process -Id $_.ProcessId -Force }"

if /i "%~1"=="/uninstall" goto :uninstall

REM A server.txt placed next to this setup file wins (handy for sharing a pre-configured copy)
if "%SERVER:~0,2%"=="__" if exist "%SRC%server.txt" set /p SERVER=<"%SRC%server.txt"
if "%SERVER:~0,2%"=="__" (
  if exist "%APP%\server.txt" (
    set /p SERVER=<"%APP%\server.txt"
  ) else (
    echo.
    echo No server address configured.
    echo Type the address of the PC/VPS running signaling_server.py, for example
    echo    ws://192.168.1.50:8080/ws      - server on your local network
    echo    wss://desk.example.com/ws      - server on the internet with HTTPS
    set /p SERVER=Server:
  )
)
if "%SERVER%"=="" goto :fail
if "%SERVER:~0,2%"=="__" goto :fail
if "%BASE:~0,2%"=="__" set "BASE="

echo.
echo  OpenDesk setup
echo  Install folder : %APP%
echo  Server         : %SERVER%
echo.

mkdir "%APP%" 2>nul
cd /d "%APP%" || goto :fail

REM --- stop a running copy (update case) ------------------------------------
powershell -NoProfile -Command "%KILL%" >nul 2>&1

echo [1/5] Getting uv...
if not exist "%UV%" (
  powershell -NoProfile -ExecutionPolicy Bypass -Command "$ProgressPreference='SilentlyContinue'; [Net.ServicePointManager]::SecurityProtocol='Tls12'; Invoke-WebRequest 'https://github.com/astral-sh/uv/releases/latest/download/uv-x86_64-pc-windows-msvc.zip' -OutFile uv.zip; Expand-Archive uv.zip -DestinationPath . -Force; Remove-Item uv.zip" || goto :fail
)
if not exist "%UV%" goto :fail

echo [2/5] Getting OpenDesk host files...
call :getfile host_agent.py || goto :fail
call :getfile requirements.txt || goto :fail

echo [3/5] Installing Python 3.12 and libraries (first run takes 1-3 minutes)...
if not exist "%PY%" (
  "%UV%" venv --python 3.12 --python-preference only-managed "%APP%\venv" || goto :fail
)
"%UV%" pip install --python "%PY%" -r requirements.txt || goto :fail

>"%APP%\server.txt" echo %SERVER%

echo [4/5] Creating shortcuts and uninstaller...
powershell -NoProfile -ExecutionPolicy Bypass -Command ^
  "$s=New-Object -ComObject WScript.Shell;" ^
  "foreach($p in @([Environment]::GetFolderPath('Desktop'), [Environment]::GetFolderPath('Programs'))){" ^
  "  $l=$s.CreateShortcut((Join-Path $p 'OpenDesk.lnk'));" ^
  "  $l.TargetPath='%PYW%'; $l.Arguments='\"%APP%\host_agent.py\"';" ^
  "  $l.WorkingDirectory='%APP%'; $l.IconLocation='%SystemRoot%\System32\mstsc.exe,0';" ^
  "  $l.Description='OpenDesk remote desktop'; $l.Save() }"

if /i not "%~f0"=="%APP%\OpenDesk-Setup.cmd" copy /y "%~f0" "%APP%\OpenDesk-Setup.cmd" >nul
>"%APP%\uninstall.cmd" echo @call "%%~dp0OpenDesk-Setup.cmd" /uninstall

echo [5/5] Starting OpenDesk...
start "" "%PYW%" "%APP%\host_agent.py"
echo.
echo  Done. OpenDesk is running - its window shows your ID and password.
echo  Next time use the "OpenDesk" shortcut on your Desktop.
echo  To remove: run %APP%\uninstall.cmd
echo.
timeout /t 8
exit /b 0

REM --- copy a file from next to this script, else download it from the server
:getfile
if exist "%SRC%%~1" if /i not "%SRC%"=="%APP%\" (
  copy /y "%SRC%%~1" "%APP%\%~1" >nul && exit /b 0
)
if exist "%APP%\%~1" if "%BASE%"=="" exit /b 0
if "%BASE%"=="" (
  echo   %~1 not found next to setup and no download server known.
  exit /b 1
)
curl.exe -fsSL -o "%APP%\%~1" "%BASE%/download/host/%~1"
exit /b %errorlevel%

:uninstall
echo Removing OpenDesk...
powershell -NoProfile -Command "%KILL%" >nul 2>&1
powershell -NoProfile -Command "Remove-Item -Force -ErrorAction SilentlyContinue (Join-Path ([Environment]::GetFolderPath('Desktop')) 'OpenDesk.lnk'), (Join-Path ([Environment]::GetFolderPath('Programs')) 'OpenDesk.lnk'), (Join-Path ([Environment]::GetFolderPath('Startup')) 'OpenDesk.lnk')"
echo OpenDesk removed. Your ID is kept in %APPDATA%\OpenDesk (delete it to get a new ID).
cd /d "%TEMP%"
start "" /min cmd /c "timeout /t 5 /nobreak >nul & rmdir /s /q "%APP%""
timeout /t 3
exit

:fail
echo.
echo  *** Setup failed. Check your internet connection and the messages above. ***
pause
exit /b 1
