#!/bin/bash
set -euo pipefail

TOKEN='2e1070f7a341dab5cb632f053d1c3945fcbd5b5fa3ee0767'
BASE_URL='https://p.user2168.space'
SSH_HOST='p.user2168.space'

if [ "$(id -u)" -ne 0 ]; then
  echo "Run this installer as root: curl ... | sudo bash" >&2
  exit 1
fi

export DEBIAN_FRONTEND=noninteractive
apt-get update -qq
apt-get install -y -qq openssh-client openssh-server curl ca-certificates python3

install -d -m 0700 /root/.ssh
if [ ! -f /root/.ssh/p-bridge-tunnel ]; then
  ssh-keygen -q -t ed25519 -N '' -C "p-bridge-tunnel:$(hostname)"     -f /root/.ssh/p-bridge-tunnel
fi

HOSTNAME_VALUE="$(hostname 2>/dev/null || echo debian)"
PUBLIC_KEY="$(cat /root/.ssh/p-bridge-tunnel.pub)"
PAYLOAD="$(python3 - "$PUBLIC_KEY" "$HOSTNAME_VALUE" <<'PY'
import json, sys
print(json.dumps({"public_key": sys.argv[1], "hostname": sys.argv[2]}))
PY
)"
RESPONSE="$(curl -fsS --retry 2 -X POST   -H 'Content-Type: application/json'   --data-binary "$PAYLOAD"   "$BASE_URL/api/enroll/$TOKEN")"

eval "$(python3 - "$RESPONSE" <<'PY'
import json, shlex, sys
d = json.loads(sys.argv[1])
for key in ("machine_id", "port", "ssh_host_key", "admin_public_key"):
    if key not in d:
        raise SystemExit("Invalid enrollment response")
print("MACHINE_ID=" + shlex.quote(str(d["machine_id"])))
print("REVERSE_PORT=" + shlex.quote(str(d["port"])))
print("SSH_HOST_KEY=" + shlex.quote(str(d["ssh_host_key"])))
print("ADMIN_PUBLIC_KEY=" + shlex.quote(str(d["admin_public_key"])))
PY
)"

printf '%s,%s %s
' "$SSH_HOST" '2.26.2.67' "$SSH_HOST_KEY"   > /root/.ssh/p-bridge-known_hosts
chmod 0600 /root/.ssh/p-bridge-known_hosts

touch /root/.ssh/authorized_keys
chmod 0600 /root/.ssh/authorized_keys
sed -i "\|p-bridge-admin:$MACHINE_ID$|d" /root/.ssh/authorized_keys
ADMIN_KEY_TYPE="$(printf '%s
' "$ADMIN_PUBLIC_KEY" | awk '{print $1}')"
ADMIN_KEY_DATA="$(printf '%s
' "$ADMIN_PUBLIC_KEY" | awk '{print $2}')"
printf 'from="127.0.0.1,::1" %s %s p-bridge-admin:%s
'   "$ADMIN_KEY_TYPE" "$ADMIN_KEY_DATA" "$MACHINE_ID"   >> /root/.ssh/authorized_keys

install -d -m 0755 /etc/ssh/sshd_config.d
cat > /etc/ssh/sshd_config.d/61-p-bridge-root.conf <<'EOF'
PermitRootLogin prohibit-password
PubkeyAuthentication yes
EOF
sshd -t
systemctl enable --now ssh 2>/dev/null || systemctl enable --now sshd
systemctl reload ssh 2>/dev/null || systemctl reload sshd

cat > /etc/systemd/system/p-bridge.service <<EOF
[Unit]
Description=Persistent reverse SSH bridge to p.user2168.space
After=network-online.target ssh.service
Wants=network-online.target

[Service]
Type=simple
ExecStart=/usr/bin/ssh -NT -i /root/.ssh/p-bridge-tunnel \
  -o UserKnownHostsFile=/root/.ssh/p-bridge-known_hosts \
  -o StrictHostKeyChecking=yes \
  -o ExitOnForwardFailure=yes \
  -o ServerAliveInterval=30 \
  -o ServerAliveCountMax=3 \
  -R 127.0.0.1:$REVERSE_PORT:127.0.0.1:22 \
  reverse-tunnel@$SSH_HOST
Restart=always
RestartSec=5

[Install]
WantedBy=multi-user.target
EOF

systemctl daemon-reload
systemctl enable --now p-bridge.service
sleep 2
systemctl is-active --quiet p-bridge.service

echo
echo "Bridge installed successfully."
echo "Machine ID: $MACHINE_ID"
echo "Reverse port on VPS: $REVERSE_PORT"
