@echo off
setlocal EnableDelayedExpansion

:: ─────────────────────────────────────────────────────────
::  StreamMesh Setup — Double-click and done
::  Self-elevates to admin, installs everything, makes shortcuts
:: ─────────────────────────────────────────────────────────

:: Auto-elevate to admin (the one UAC "Yes" click they need)
net session >nul 2>&1
if %errorlevel% neq 0 (
    echo Requesting admin permission...
    powershell -Command "Start-Process -Verb RunAs -FilePath '%~f0' -ArgumentList '%~dp0'"
    exit /b
)

:: We're admin now
cd /d "%~dp0"
title StreamMesh Setup
color 0B

cls
echo.
echo   ============================================
echo   =                                          =
echo   =        StreamMesh  -  Quick Setup        =
echo   =                                          =
echo   ============================================
echo.
echo   This sets up a small, safe background tool
echo   that shares a tiny bit of your internet
echo   bandwidth with Josh's private network.
echo.
echo   It installs two things:
echo     - WireGuard (encrypted tunnel, used by millions)
echo     - microsocks (tiny proxy, 50 KB)
echo.
echo   You get desktop shortcuts to Start and Stop
echo   it whenever you want. Nothing hidden.
echo.
echo   Everything goes into:
echo     C:\ProgramData\StreamMesh
echo.

set /p "CONFIRM=  Ready to install? (Y/N): "
if /i not "%CONFIRM%"=="Y" (
    echo.
    echo   No worries, nothing was installed.
    pause
    exit /b
)

echo.
echo   ────────────────────────────────────────────
echo   Paste the invite key Josh sent you.
echo   (right-click to paste, then press Enter)
echo   ────────────────────────────────────────────
echo.
set /p "MESHKEY=  Invite key: "

if "%MESHKEY%"=="" (
    echo.
    echo   No key entered. Ask Josh for your invite key.
    pause
    exit /b
)

:: ── Decode the invite key ──
echo.
echo   [1/5] Decoding invite key...

:: Use PowerShell to decode base64 JSON (bat can't do this alone)
set "DECODE_CMD=powershell -NoProfile -Command "$d=[Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('%MESHKEY%'));$j=$d|ConvertFrom-Json;Write-Output \"$($j.hub_endpoint)|$($j.hub_pubkey)|$($j.peer_ip)|$($j.peer_privkey)|$($j.proxy_port)\"""

for /f "tokens=1-5 delims=|" %%a in ('%DECODE_CMD%') do (
    set "HUB_ENDPOINT=%%a"
    set "HUB_PUBKEY=%%b"
    set "PEER_IP=%%c"
    set "PEER_PRIVKEY=%%d"
    set "PROXY_PORT=%%e"
)

if "%PEER_IP%"=="" (
    echo.
    echo   Bad invite key. Ask Josh for a new one.
    pause
    exit /b
)

echo   Your mesh address: %PEER_IP%
echo   Proxy port: %PROXY_PORT%
echo.

:: ── Create install directory ──
set "INSTALL_DIR=C:\ProgramData\StreamMesh"
if not exist "%INSTALL_DIR%" mkdir "%INSTALL_DIR%"

:: ── Install WireGuard ──
echo   [2/5] Installing WireGuard...

where wg >nul 2>&1
if %errorlevel% neq 0 (
    echo     Downloading WireGuard...
    powershell -NoProfile -Command "Invoke-WebRequest -Uri 'https://download.wireguard.com/windows-client/wireguard-installer.exe' -OutFile '%TEMP%\wg-install.exe' -UseBasicParsing"
    echo.
    echo   ============================================
    echo   The WireGuard installer will open now.
    echo   Just click through it normally.
    echo   Come back here when it's done.
    echo   ============================================
    echo.
    start /wait "" "%TEMP%\wg-install.exe"
    del "%TEMP%\wg-install.exe" >nul 2>&1
    echo     WireGuard installed.
) else (
    echo     WireGuard already installed.
)
echo.

:: ── Write WireGuard config ──
echo   [3/5] Configuring mesh tunnel...

(
echo [Interface]
echo PrivateKey = %PEER_PRIVKEY%
echo Address = %PEER_IP%/24
echo DNS = 1.1.1.1
echo.
echo [Peer]
echo PublicKey = %HUB_PUBKEY%
echo Endpoint = %HUB_ENDPOINT%
echo AllowedIPs = 10.0.0.0/16
echo PersistentKeepalive = 25
) > "%INSTALL_DIR%\streammesh.conf"

:: Try to auto-import into WireGuard
if exist "C:\Program Files\WireGuard\wireguard.exe" (
    "C:\Program Files\WireGuard\wireguard.exe" /installtunnelservice "%INSTALL_DIR%\streammesh.conf" >nul 2>&1
    echo     Tunnel configured.
) else (
    echo     Open WireGuard and import: %INSTALL_DIR%\streammesh.conf
)
echo.

:: ── Download microsocks ──
echo   [4/5] Downloading microsocks (tiny proxy)...

if not exist "%INSTALL_DIR%\microsocks.exe" (
    powershell -NoProfile -Command "try { Invoke-WebRequest -Uri 'https://github.com/nicedreams/microsocks-windows/releases/download/v1.0.4/microsocks.exe' -OutFile '%INSTALL_DIR%\microsocks.exe' -UseBasicParsing; Write-Host '    Downloaded.' } catch { Write-Host '    Download failed - will retry from backup...' }"

    if not exist "%INSTALL_DIR%\microsocks.exe" (
        echo     Trying backup download...
        powershell -NoProfile -Command "Invoke-WebRequest -Uri 'https://babit.ai/microsocks.exe' -OutFile '%INSTALL_DIR%\microsocks.exe' -UseBasicParsing" >nul 2>&1
    )
) else (
    echo     Already downloaded.
)
echo.

:: ── Create Start / Stop / Uninstall scripts ──
echo   [5/5] Creating desktop shortcuts...

:: START script
(
echo @echo off
echo title StreamMesh
echo color 0A
echo echo.
echo echo   StreamMesh is running.
echo echo   Sharing bandwidth on port %PROXY_PORT%
echo echo.
echo echo   Leave this window open, or minimize it.
echo echo   Close it to stop sharing.
echo echo.
echo start "" /B "%INSTALL_DIR%\microsocks.exe" -i 0.0.0.0 -p %PROXY_PORT%
echo echo   Status: ACTIVE
echo echo.
echo pause
echo taskkill /F /IM microsocks.exe ^>nul 2^>^&1
) > "%INSTALL_DIR%\start.bat"

:: STOP script
(
echo @echo off
echo taskkill /F /IM microsocks.exe ^>nul 2^>^&1
echo echo StreamMesh stopped.
echo timeout /t 2
) > "%INSTALL_DIR%\stop.bat"

:: UNINSTALL script
(
echo @echo off
echo echo Uninstalling StreamMesh...
echo taskkill /F /IM microsocks.exe ^>nul 2^>^&1
echo if exist "C:\Program Files\WireGuard\wireguard.exe" "C:\Program Files\WireGuard\wireguard.exe" /uninstalltunnelservice streammesh ^>nul 2^>^&1
echo rmdir /s /q "%INSTALL_DIR%"
echo echo Done. WireGuard left installed ^(remove from Settings if you want^).
echo pause
) > "%INSTALL_DIR%\uninstall.bat"

:: Desktop shortcuts (using PowerShell because bat can't make .lnk)
powershell -NoProfile -Command "$s=(New-Object -COM WScript.Shell).CreateShortcut([Environment]::GetFolderPath('Desktop')+'\StreamMesh Start.lnk');$s.TargetPath='%INSTALL_DIR%\start.bat';$s.WorkingDirectory='%INSTALL_DIR%';$s.IconLocation='shell32.dll,172';$s.Save()"
powershell -NoProfile -Command "$s=(New-Object -COM WScript.Shell).CreateShortcut([Environment]::GetFolderPath('Desktop')+'\StreamMesh Stop.lnk');$s.TargetPath='%INSTALL_DIR%\stop.bat';$s.WorkingDirectory='%INSTALL_DIR%';$s.IconLocation='shell32.dll,131';$s.Save()"

echo     Desktop shortcuts created.
echo.

:: ── Done ──
color 0A
echo.
echo   ============================================
echo   =                                          =
echo   =          Setup Complete!                  =
echo   =                                          =
echo   ============================================
echo.
echo   Your mesh address:  %PEER_IP%
echo   Proxy port:         %PROXY_PORT%
echo.
echo   Two shortcuts are on your desktop:
echo.
echo     [StreamMesh Start]  - begin sharing
echo     [StreamMesh Stop]   - pause sharing
echo.
echo   Double-click "StreamMesh Start" to begin!
echo.
echo   To uninstall later, run:
echo     %INSTALL_DIR%\uninstall.bat
echo.

pause
