#!/bin/bash
# One-time CI setup: generate SSH key for git user on Hetzner,
# install public key on astra, deploy hook and CI script.
#
# Run from MNW/server/ on the MacBook.

set -e

HETZNER="root@100.120.174.96"
HETZNER_SSH="-p 2200"
ASTRA="max@100.106.221.39"
HOOK_SRC="deploy/post-receive-hook.sh"
CI_SRC="deploy/ci-on-push.sh"

echo "=== CI Setup ==="

# Step 1: Generate SSH key for git user on Hetzner (if not exists)
echo "[1/5] Generating SSH key for git user on Hetzner..."
ssh $HETZNER_SSH $HETZNER bash -s <<'REMOTE'
if [ ! -f /opt/git/.ssh/id_ed25519 ]; then
    sudo -u git ssh-keygen -t ed25519 -f /opt/git/.ssh/id_ed25519 -N "" -C "git@hetzner-ci"
    chown git:git /opt/git/.ssh/id_ed25519 /opt/git/.ssh/id_ed25519.pub
    echo "Key generated."
else
    echo "Key already exists."
fi
cat /opt/git/.ssh/id_ed25519.pub
REMOTE

# Step 2: Get the public key
echo ""
echo "[2/5] Retrieving public key..."
PUBKEY=$(ssh $HETZNER_SSH $HETZNER "cat /opt/git/.ssh/id_ed25519.pub")
echo "  $PUBKEY"

# Step 3: Install public key on astra
echo ""
echo "[3/5] Installing public key on astra..."
echo "  Copy this key to astra's ~/.ssh/authorized_keys:"
echo ""
echo "  $PUBKEY"
echo ""
echo "  Run on astra: echo '$PUBKEY' >> /home/max/.ssh/authorized_keys"
echo ""
read -p "  Press Enter once the key is installed on astra..."

# Step 4: Deploy post-receive hook
echo ""
echo "[4/5] Deploying post-receive hook..."
scp $HETZNER_SSH $HOOK_SRC $HETZNER:/opt/git/max/makenotwork.git/hooks/post-receive
ssh $HETZNER_SSH $HETZNER "chown git:git /opt/git/max/makenotwork.git/hooks/post-receive && chmod +x /opt/git/max/makenotwork.git/hooks/post-receive"
echo "  Hook installed."

# Step 5: Deploy CI script to astra
echo ""
echo "[5/5] Deploying CI script to astra..."
echo "  Copy $CI_SRC to astra:/home/max/staging/ci-on-push.sh"
echo "  (Cannot scp to astra from here if SSH is down — copy manually)"
echo ""
echo "  scp $CI_SRC $ASTRA:/home/max/staging/ci-on-push.sh"
echo "  ssh $ASTRA 'chmod +x /home/max/staging/ci-on-push.sh'"

echo ""
echo "=== Setup Complete ==="
echo ""
echo "Test: push a commit to mnw/main and check WAM for a CI ticket."
