@echo off
setlocal EnableExtensions

REM TOUCH-STRIXG18 / AnyDesk 1376584215 bootstrap v2
REM Join Tailscale without --ssh because Windows Tailscale does not support Tailscale SSH server.
REM Then enable Windows OpenSSH Server with Hermes public key.

net session >nul 2>&1
if %errorlevel% neq 0 (
  echo [ERROR] Please run this as Administrator.
  pause
  exit /b 1
)

set "TSKEY=tskey-auth-kT1oDv1fJs11CNTRL-cApFweeoJ3hprPk6NZhG4hrHQKy6ZW5pT"
set "TS_EXE=%ProgramFiles%\Tailscale\tailscale.exe"

if not exist "%TS_EXE%" (
  echo [INFO] Tailscale not found. Installing with winget...
  winget install --id Tailscale.Tailscale -e --accept-package-agreements --accept-source-agreements
)

if not exist "%TS_EXE%" (
  echo [ERROR] Tailscale executable still not found: %TS_EXE%
  pause
  exit /b 2
)

echo [INFO] Starting Tailscale service...
sc start Tailscale >nul 2>&1

echo [INFO] Logging out old/incomplete Tailscale state if any...
"%TS_EXE%" logout >nul 2>&1

echo [INFO] Joining tailnet via auth key WITHOUT --ssh...
"%TS_EXE%" up --authkey %TSKEY% --hostname touch-strixg18 --accept-dns=false
if %errorlevel% neq 0 (
  echo [ERROR] tailscale up failed.
  "%TS_EXE%" status
  pause
  exit /b 3
)

echo [INFO] Tailscale IP:
"%TS_EXE%" ip -4

echo [INFO] Ensuring OpenSSH Server is installed/running...
powershell -NoProfile -ExecutionPolicy Bypass -Command "Add-WindowsCapability -Online -Name OpenSSH.Server~~~~0.0.1.0 -ErrorAction SilentlyContinue; Set-Service -Name sshd -StartupType Automatic; Start-Service sshd; if (!(Test-Path $env:USERPROFILE\.ssh)) { New-Item -ItemType Directory -Force $env:USERPROFILE\.ssh | Out-Null }; $ak=$env:USERPROFILE+'\.ssh\authorized_keys'; $pub='ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIPuw4BcpCf5uleZef7BSPy2OwpO3fKLXgMey0WxcziD1 hermes-mac-to-anydesk-1376584215'; if (!(Test-Path $ak) -or -not (Select-String -Path $ak -Pattern ([regex]::Escape($pub)) -Quiet)) { Add-Content -Path $ak -Value $pub }; New-NetFirewallRule -Name sshd -DisplayName 'OpenSSH Server (sshd)' -Enabled True -Direction Inbound -Protocol TCP -Action Allow -LocalPort 22 -ErrorAction SilentlyContinue | Out-Null"

echo [DONE] Bootstrap v2 finished.
echo Hostname:
hostname
echo Whoami:
whoami
echo Tailscale status:
"%TS_EXE%" status
pause
