"""Launch login in detached mode, container persists independent of SSH."""
import paramiko, socket

HOST, USER = "172.16.3.20", "root"
import subprocess as _sp, yaml as _y
PWD = _y.safe_load(_sp.run(["sops","-d","D:/vault/infrastructure/jupiter-unraid-primary.sops.yaml"],capture_output=True,text=True,timeout=30,check=True).stdout)["credentials"]["password"]
APPDATA = '/mnt/cache/appdata/cloudflared'

SCRIPT = f'''
docker rm -f cf-login 2>/dev/null
docker run -d --name cf-login \\
    -v {APPDATA}:/home/nonroot/.cloudflared \\
    cloudflare/cloudflared:latest tunnel login
sleep 4
echo "=== logs ==="
docker logs cf-login 2>&1
'''

socket.setdefaulttimeout(60)
c = paramiko.SSHClient(); c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(HOST, username=USER, password=PWD, timeout=30, look_for_keys=False, allow_agent=False)
_, o, e = c.exec_command(SCRIPT, timeout=90)
print(o.read().decode('utf-8','replace').rstrip())
print(e.read().decode('utf-8','replace').rstrip())
c.close()
