@echo off
setlocal EnableDelayedExpansion

REM ============================================================
REM Phase 7.x Reverse-Tunnel Wizard — Multi-Device (Pool 22222..22240)
REM
REM Reihenfolge:
REM   1. Tunnel-Keypair generieren (falls noch nicht da)
REM   2. Pubkey + Hostname an Agent /tunnel/register POSTen
REM      -> Agent vergibt freien Pool-Port, in adb_tunnel_port.txt schreiben
REM   3. Port-Datei einlesen in TUN_REMOTE_PORT
REM   4. Alte ssh.exe Tunnel-Prozesse mit gleichem Key beenden
REM   5. SSH-Reverse-Tunnel im Hintergrund starten
REM   6. Status pollen + alles in Outfile + Auto-Send an Agent
REM ============================================================

set "OUTFILE=%USERPROFILE%\Desktop\PHASE7X_REVERSE_TUNNEL.txt"
set "SSH_DIR=%USERPROFILE%\.ssh"
set "TUN_KEY=%SSH_DIR%\adb_tunnel_id_ed25519"
set "TUN_PUB=%TUN_KEY%.pub"
set "PORT_FILE=%SSH_DIR%\adb_tunnel_port.txt"
set "AGENT_HOST=bridge.xxbillion.ai"
set "AGENT_USER=root"
set "TUN_LOCAL_PORT=22"

if not exist "%SSH_DIR%" mkdir "%SSH_DIR%" >nul 2>&1

REM Outfile zuruecksetzen
echo. > "%OUTFILE%"
echo ============================================ >> "%OUTFILE%"
echo Phase 7.x Reverse-Tunnel Wizard >> "%OUTFILE%"
echo Datum: %DATE% %TIME% >> "%OUTFILE%"
echo Host : %COMPUTERNAME% >> "%OUTFILE%"
echo User : %USERDOMAIN%\%USERNAME% >> "%OUTFILE%"
echo ============================================ >> "%OUTFILE%"
echo. >> "%OUTFILE%"

REM ── Schritt 1: Keypair ────────────────────────────────
echo --- 1. Tunnel-Keypair vorhanden? --- >> "%OUTFILE%"
if exist "%TUN_KEY%" (
    echo Keypair bereits vorhanden: %TUN_KEY% >> "%OUTFILE%"
) else (
    echo Erzeuge neues ed25519-Keypair ... >> "%OUTFILE%"
    ssh-keygen -t ed25519 -N "" -C "phase7x-tunnel-from-%COMPUTERNAME%" -f "%TUN_KEY%" >nul 2>&1
    if exist "%TUN_KEY%" (
        echo Keypair angelegt: %TUN_KEY% >> "%OUTFILE%"
    ) else (
        echo FEHLER: ssh-keygen schlug fehl >> "%OUTFILE%"
    )
)
echo. >> "%OUTFILE%"

REM ── Schritt 2: Pubkey registrieren + Port-File schreiben ─
echo --- 2. Public-Key registrieren + Port aus Pool holen --- >> "%OUTFILE%"
powershell -NoProfile -ExecutionPolicy Bypass -Command "try { $p = Get-Content -Raw -Encoding UTF8 -Path '%TUN_PUB%'; $r = Invoke-RestMethod -Method POST -Uri ('https://%AGENT_HOST%/tunnel/register?device=' + $env:COMPUTERNAME) -ContentType 'text/plain; charset=utf-8' -Body $p -TimeoutSec 15; Write-Output ('OK -- Agent angenommen: already_present=' + $r.already_present + ' tunnel_remote_port=' + $r.tunnel_remote_port); Set-Content -Path '%PORT_FILE%' -Value $r.tunnel_remote_port -NoNewline -Encoding ASCII } catch { Write-Output ('FEHLER /tunnel/register: ' + $_.Exception.Message) }" >> "%OUTFILE%" 2>&1
echo. >> "%OUTFILE%"

REM ── Schritt 3: Port-File einlesen ────────────────────
set "TUN_REMOTE_PORT="
if exist "%PORT_FILE%" (
    set /p TUN_REMOTE_PORT=<"%PORT_FILE%"
)
if not defined TUN_REMOTE_PORT (
    echo FEHLER: Konnte tunnel_remote_port nicht ermitteln. Abbruch. >> "%OUTFILE%"
    goto :send
)
echo Zugewiesener Pool-Port: !TUN_REMOTE_PORT! >> "%OUTFILE%"
echo. >> "%OUTFILE%"

REM ── Schritt 4: Alte Tunnel-Prozesse killen ───────────
echo --- 3. Alte ssh.exe Tunnel-Prozesse beenden --- >> "%OUTFILE%"
for /f "tokens=2 delims==" %%P in ('wmic process where "name='ssh.exe' and commandline like '%%adb_tunnel_id_ed25519%%'" get processid /value 2^>nul ^| find "="') do (
    taskkill /F /PID %%P >nul 2>&1
    echo Alter Tunnel-PID %%P beendet >> "%OUTFILE%"
)
echo. >> "%OUTFILE%"

REM ── Schritt 5: Reverse-Tunnel starten ────────────────
echo --- 4. Reverse-Tunnel starten ^(Hintergrund^) --- >> "%OUTFILE%"
echo Befehl: ssh -i %TUN_KEY% -fN -R !TUN_REMOTE_PORT!:127.0.0.1:%TUN_LOCAL_PORT% %AGENT_USER%@%AGENT_HOST% >> "%OUTFILE%"
powershell -NoProfile -Command "Start-Process -FilePath 'ssh.exe' -ArgumentList @('-i','%TUN_KEY%','-o','StrictHostKeyChecking=accept-new','-o','UserKnownHostsFile=%SSH_DIR%\adb_known_hosts','-o','ServerAliveInterval=30','-o','ServerAliveCountMax=3','-o','ExitOnForwardFailure=yes','-N','-R','!TUN_REMOTE_PORT!:127.0.0.1:%TUN_LOCAL_PORT%','%AGENT_USER%@%AGENT_HOST%') -WindowStyle Hidden -PassThru | ForEach-Object { Write-Output ('Tunnel-PID: ' + $_.Id) }" >> "%OUTFILE%" 2>&1
echo. >> "%OUTFILE%"

REM ── Schritt 6: Status pollen ─────────────────────────
echo --- 5. 5s warten + Status pollen --- >> "%OUTFILE%"
timeout /t 5 /nobreak >nul
powershell -NoProfile -Command "$ssh = Get-Process ssh -ErrorAction SilentlyContinue; if ($ssh) { Write-Output ('ssh.exe laeuft: PID=' + ($ssh.Id -join ',')) } else { Write-Output 'ssh.exe NICHT mehr im Prozess-Pool' }" >> "%OUTFILE%" 2>&1
powershell -NoProfile -ExecutionPolicy Bypass -Command "try { $r = Invoke-RestMethod -Uri ('https://%AGENT_HOST%/tunnel/status?port=!TUN_REMOTE_PORT!') -TimeoutSec 5; Write-Output ('Agent sieht Tunnel auf Port !TUN_REMOTE_PORT!: port_open=' + $r.port_open + ' banner=' + $r.banner) } catch { Write-Output ('Status-Abruf Fehler: ' + $_.Exception.Message) }" >> "%OUTFILE%" 2>&1
echo. >> "%OUTFILE%"

:send
echo ============================================ >> "%OUTFILE%"
echo ENDE >> "%OUTFILE%"
echo ============================================ >> "%OUTFILE%"

type "%OUTFILE%"

echo.
echo --- Auto-Send an Agent ---
powershell -NoProfile -ExecutionPolicy Bypass -Command "try { $b = Get-Content -Raw -Encoding UTF8 -Path '%OUTFILE%'; $r = Invoke-RestMethod -Method POST -Uri 'https://%AGENT_HOST%/submit' -ContentType 'text/plain; charset=utf-8' -Body $b -TimeoutSec 15; Write-Host ('OK -- Agent hat es: id=' + $r.id) -ForegroundColor Green } catch { Write-Host ('FEHLER Auto-Send: ' + $_.Exception.Message) -ForegroundColor Red }"

type "%OUTFILE%" | clip

echo.
echo ###################################################
echo #   FERTIG.                                       #
echo #   Tunnel laeuft im Hintergrund.                 #
echo #   Bei Neustart einfach diese Datei nochmal      #
echo #   doppelklicken.                                #
echo ###################################################
echo.
pause
