@echo off
setlocal EnableDelayedExpansion

REM ============================================================
REM Phase 7.x SSH-Setup Wizard
REM
REM Was es macht:
REM   1. OpenSSH-Server installieren (Windows-Capability)
REM   2. Service sshd starten + Auto-Start
REM   3. Firewall-Regel fuer TCP 22
REM   4. Agent-Pubkey in C:\Users\%USERNAME%\.ssh\authorized_keys
REM   5. Output Schritt-fuer-Schritt + landet in der Zwischenablage
REM
REM WICHTIG:
REM   Diese Datei MUSS als Administrator laufen.
REM   Rechtsklick auf die Datei -> "Als Administrator ausfuehren".
REM ============================================================

set "OUTFILE=%USERPROFILE%\Desktop\PHASE7X_SSH_SETUP.txt"
set "PUBKEY=ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIHHnVdZo59KSZ7R8T7cN+AFXx5nMd06vq/5nx36xVX2X linux-host-to-windows-workstation-01"

REM Admin-Check
net session >nul 2>&1
if not "%ERRORLEVEL%"=="0" (
    echo.
    echo ===============================================
    echo  FEHLER: NICHT ALS ADMINISTRATOR GESTARTET.
    echo ===============================================
    echo.
    echo  So gehts richtig:
    echo    1. Datei NICHT doppelklicken
    echo    2. Rechtsklick auf die Datei
    echo    3. "Als Administrator ausfuehren"
    echo    4. UAC-Frage mit Ja bestaetigen
    echo.
    pause
    exit /b 1
)

(
echo ============================================
echo Phase 7.x SSH-Setup Wizard
echo Datum: %DATE% %TIME%
echo User : %USERDOMAIN%\%USERNAME%
echo ============================================
echo.

echo --- 1. OpenSSH-Server Capability ---
powershell -NoProfile -Command "$c=Get-WindowsCapability -Online -Name 'OpenSSH.Server*' -ErrorAction SilentlyContinue; if ($c.State -eq 'Installed') { 'bereits installiert' } else { try { Add-WindowsCapability -Online -Name $c.Name | Out-Null; 'INSTALLIERT' } catch { 'FEHLER: ' + $_.Exception.Message } }"
echo.

echo --- 2. sshd Service: Start + Auto-Start ---
powershell -NoProfile -Command "try { Set-Service -Name sshd -StartupType Automatic -ErrorAction Stop; Start-Service -Name sshd -ErrorAction Stop; (Get-Service sshd | Format-Table -AutoSize Name,Status,StartType | Out-String).Trim() } catch { 'FEHLER: ' + $_.Exception.Message }"
echo.

echo --- 3. Firewall-Regel fuer Port 22 ---
powershell -NoProfile -Command "$r=Get-NetFirewallRule -Name 'OpenSSH-Server-In-TCP' -ErrorAction SilentlyContinue; if (-not $r) { try { New-NetFirewallRule -Name 'OpenSSH-Server-In-TCP' -DisplayName 'OpenSSH Server (sshd)' -Enabled True -Direction Inbound -Protocol TCP -Action Allow -LocalPort 22 | Out-Null; 'REGEL ANGELEGT' } catch { 'FEHLER: ' + $_.Exception.Message } } else { 'Regel existiert bereits: ' + $r.DisplayName }"
echo.

echo --- 4. Agent-Pubkey in authorized_keys ---
set "SSH_DIR=%USERPROFILE%\.ssh"
set "AUTH_KEYS=%SSH_DIR%\authorized_keys"
if not exist "%SSH_DIR%" mkdir "%SSH_DIR%" >nul 2>&1
findstr /C:"%PUBKEY%" "%AUTH_KEYS%" >nul 2>&1
if "%ERRORLEVEL%"=="0" (
    echo Pubkey bereits in authorized_keys vorhanden.
) else (
    >>"%AUTH_KEYS%" echo %PUBKEY%
    echo Pubkey zu authorized_keys hinzugefuegt: %AUTH_KEYS%
)
echo.

echo --- 4b. ACL fix auf authorized_keys ^(nur User + SYSTEM lesen^) ---
powershell -NoProfile -Command "try { icacls '%AUTH_KEYS%' /inheritance:r /grant '%USERNAME%:(R,W)' /grant 'SYSTEM:(R,W)' /remove 'Authenticated Users' /remove 'Users' 2^>$null | Out-Null; 'ACL gesetzt' } catch { 'FEHLER ACL: ' + $_.Exception.Message }"
echo.

echo --- 4c. ADMIN-Sonderfall: bei lokalen Admins liest sshd aus C:\ProgramData\ssh\administrators_authorized_keys ---
powershell -NoProfile -Command "$isAdmin=([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator); if ($isAdmin) { $f='C:\ProgramData\ssh\administrators_authorized_keys'; if (-not (Test-Path 'C:\ProgramData\ssh')) { New-Item -ItemType Directory -Path 'C:\ProgramData\ssh' -Force | Out-Null }; if ((Test-Path $f) -and (Select-String -Path $f -SimpleMatch '%PUBKEY%' -Quiet)) { 'Pubkey bereits in administrators_authorized_keys' } else { Add-Content -Path $f -Value '%PUBKEY%'; icacls $f /inheritance:r /grant 'SYSTEM:(F)' /grant 'Administrators:(F)' 2^>$null | Out-Null; 'Pubkey in administrators_authorized_keys angelegt + ACL gesetzt' } } else { 'User ist NICHT Admin -- administrators_authorized_keys nicht noetig' }"
echo.

echo --- 5. Aktive SSH-Listener ---
powershell -NoProfile -Command "Get-NetTCPConnection -State Listen -LocalPort 22 -ErrorAction SilentlyContinue | Format-Table -AutoSize LocalAddress,LocalPort,State | Out-String"
echo.

echo --- 6. Public-IP zur Bestaetigung ---
powershell -NoProfile -Command "try { (Invoke-WebRequest -UseBasicParsing -Uri 'https://api.ipify.org' -TimeoutSec 5).Content } catch { 'Public-IP nicht abrufbar' }"
echo.

echo ============================================
echo ENDE
echo ============================================
) > "%OUTFILE%" 2>&1

type "%OUTFILE%"

echo.
echo --- Sende automatisch an den Agent ---
powershell -NoProfile -ExecutionPolicy Bypass -Command "try { $b = Get-Content -Raw -Encoding UTF8 -Path '%OUTFILE%'; $r = Invoke-RestMethod -Method POST -Uri 'https://bridge.xxbillion.ai/submit' -ContentType 'text/plain; charset=utf-8' -Body $b -TimeoutSec 15; Write-Host ('OK -- Agent hat es: id=' + $r.id + ' (' + $r.bytes + ' bytes)') -ForegroundColor Green } catch { Write-Host ('FEHLER -- Auto-Send: ' + $_.Exception.Message) -ForegroundColor Red; Write-Host 'Fallback: Output in Zwischenablage + Datei auf Desktop -- bridge.xxbillion.ai Block IV manuell.' }"

REM Fallback: Zwischenablage
type "%OUTFILE%" | clip

echo.
echo ###################################################
echo #   FERTIG. Output ging direkt an den Agent.      #
echo #   Datei liegt zusaetzlich auf dem Desktop:      #
echo #   %OUTFILE%
echo ###################################################
echo.
pause
