#!/usr/bin/env bash
# bc250-remote-setup — one-time remote-admin setup for the BC-250 console.
#
# Run this from a terminal INSIDE the child's desktop session (not over SSH):
# GNOME Remote Desktop is configured per-user and only serves while that
# user's session is running. SSH works regardless of who is logged in.
#
# Sets up:
#   * sshd enabled + firewall opened  (headless admin: updates, shell)
#   * GNOME Remote Desktop over RDP with a self-signed TLS cert and
#     credentials you choose  (drive the desktop to install games)
#
# Secrets (RDP password, TLS key) are created here on the box — they are
# deliberately NOT part of the OS image.

set -u

bold()  { printf '\033[1m%s\033[0m\n' "$*"; }
warn()  { printf '\033[33mWARNING:\033[0m %s\n' "$*"; }
ok()    { printf '\033[32m  ok:\033[0m %s\n' "$*"; }

if [ "$(id -u)" -eq 0 ]; then
    warn "Run this as the regular desktop user, not root. Aborting."
    exit 1
fi

FW_CHANGED=0

# ---------------------------------------------------------------- SSH ------
bold "[1/3] SSH (headless admin)"

if systemctl is-enabled sshd.service >/dev/null 2>&1 && systemctl is-active sshd.service >/dev/null 2>&1; then
    ok "sshd already enabled and running"
else
    sudo systemctl enable --now sshd.service && ok "sshd enabled + started" \
        || warn "could not enable sshd — run 'sudo systemctl enable --now sshd' manually"
fi

if sudo firewall-cmd --permanent --query-service=ssh >/dev/null 2>&1; then
    ok "firewall already allows ssh"
else
    sudo firewall-cmd --permanent --add-service=ssh >/dev/null && FW_CHANGED=1 && ok "firewall: ssh service allowed" \
        || warn "could not open firewall for ssh"
fi

# ---------------------------------------------------- GNOME Remote Desktop -
bold "[2/3] GNOME Remote Desktop (RDP)"

if ! command -v grdctl >/dev/null 2>&1; then
    warn "grdctl not found — skipping RDP setup (is gnome-remote-desktop installed?)"
else
    CERT_DIR="$HOME/.local/share/gnome-remote-desktop"
    CERT="$CERT_DIR/rdp-tls.crt"
    KEY="$CERT_DIR/rdp-tls.key"
    mkdir -p "$CERT_DIR"

    if [ -s "$CERT" ] && [ -s "$KEY" ]; then
        ok "TLS cert already exists at $CERT_DIR"
    else
        openssl req -x509 -newkey rsa:4096 -nodes -days 3650 \
            -subj "/CN=bc250-console" \
            -keyout "$KEY" -out "$CERT" >/dev/null 2>&1 \
            && chmod 600 "$KEY" && ok "self-signed TLS cert generated" \
            || warn "openssl cert generation failed"
    fi

    printf 'RDP username to create: '
    read -r RDP_USER
    printf 'RDP password (input hidden): '
    read -rs RDP_PASS
    printf '\n'

    grdctl rdp set-tls-cert "$CERT" 2>/dev/null || warn "grdctl set-tls-cert failed"
    grdctl rdp set-tls-key  "$KEY"  2>/dev/null || warn "grdctl set-tls-key failed"

    # Credential syntax varies across GNOME versions — try the two common
    # forms, then fall back to telling the user to do it interactively.
    if grdctl rdp set-credentials "$RDP_USER" "$RDP_PASS" 2>/dev/null; then
        ok "RDP credentials stored"
    elif printf '%s\n%s\n' "$RDP_USER" "$RDP_PASS" | grdctl rdp set-credentials 2>/dev/null; then
        ok "RDP credentials stored (interactive form)"
    else
        warn "could not store credentials automatically — run 'grdctl rdp set-credentials' yourself"
    fi
    unset RDP_PASS

    grdctl rdp enable 2>/dev/null || warn "grdctl rdp enable failed"

    systemctl --user enable --now gnome-remote-desktop.service \
        && ok "per-user gnome-remote-desktop.service enabled" \
        || warn "could not enable gnome-remote-desktop.service for this user"

    if sudo firewall-cmd --permanent --query-port=3389/tcp >/dev/null 2>&1; then
        ok "firewall already allows 3389/tcp"
    else
        sudo firewall-cmd --permanent --add-port=3389/tcp >/dev/null && FW_CHANGED=1 && ok "firewall: 3389/tcp (RDP) allowed" \
            || warn "could not open firewall for RDP"
    fi
fi

# ------------------------------------------------------------- summary -----
bold "[3/3] Finishing up"

if [ "$FW_CHANGED" -eq 1 ]; then
    sudo firewall-cmd --reload >/dev/null && ok "firewall reloaded" || warn "firewall reload failed"
fi

echo
bold "This console's addresses:"
ip -4 -o addr show scope global | awk '{ printf "  %-12s %s\n", $2, $4 }'
if command -v tailscale >/dev/null 2>&1; then
    TS_IP="$(tailscale ip -4 2>/dev/null | head -n1)"
    if [ -n "${TS_IP:-}" ]; then
        echo "  tailscale    $TS_IP"
    else
        echo "  (tailscale installed but not up — run: sudo tailscale up)"
    fi
fi

echo
bold "How to connect:"
echo "  SSH:  ssh <your-user>@<address>          (works any time the box is on)"
echo "  RDP:  any RDP client -> <address>:3389   (only while this desktop session"
echo "        is logged in; use the RDP username/password you just set)"
echo
echo "Keep SSH/RDP LAN- or tailnet-only. Do NOT port-forward 22/3389 to the internet."
