#!/usr/bin/env bash
#
# setup-ci-deploy.sh — allow a CI server (Jenkins) to update the platform on
# THIS instance through `paas-self-deploy`. Run once per server, as root:
#
#   sudo ./infra/setup-ci-deploy.sh "ssh-ed25519 AAAA… jenkins-platform"
#
# It installs the self-deploy pieces (also done by bootstrap.sh, so a fresh
# bootstrap is not required first) and adds the given public key to the
# deploy user's authorized_keys with a forced command, so that key can do
# nothing but `deploy <commit>`, `verify`, `status`, `rollback`. Re-running
# with the same key is a no-op; a different key is added alongside.
#
# Instance state (the key) — NOT part of the golden template; the template
# only carries the scripts + sudoers, which are inert until a key is added.

set -euo pipefail
[[ "$(id -u)" -eq 0 ]] || { echo "run as root" >&2; exit 1; }
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
PUBKEY="${1:-}"
[[ "$PUBKEY" =~ ^(ssh-ed25519|ssh-rsa|ecdsa-sha2-nistp256)\ [A-Za-z0-9+/=]+ ]] \
    || { echo "usage: $0 \"<ssh public key line>\"" >&2; exit 2; }
KEY_BODY="$(awk '{print $2}' <<<"$PUBKEY")"

install -m 0755 "$SCRIPT_DIR/infra/paas-self-deploy" /usr/local/sbin/paas-self-deploy
install -m 0755 "$SCRIPT_DIR/infra/paas-ci-ssh" /usr/local/bin/paas-ci-ssh
cat >/etc/sudoers.d/paas-ci <<'EOF'
deploy ALL=(root) NOPASSWD: /usr/local/sbin/paas-self-deploy *
EOF
chmod 440 /etc/sudoers.d/paas-ci
visudo -cf /etc/sudoers.d/paas-ci >/dev/null

AK=/home/deploy/.ssh/authorized_keys
install -d -m 700 -o deploy -g deploy /home/deploy/.ssh
touch "$AK"; chown deploy:deploy "$AK"; chmod 600 "$AK"
if grep -qF "$KEY_BODY" "$AK"; then
    echo "[ci-deploy] key already authorized"
else
    printf 'restrict,command="/usr/local/bin/paas-ci-ssh" %s\n' "$PUBKEY" >>"$AK"
    echo "[ci-deploy] key added to $AK (forced command: paas-ci-ssh)"
fi

echo "[ci-deploy] installed: /usr/local/sbin/paas-self-deploy, /usr/local/bin/paas-ci-ssh, /etc/sudoers.d/paas-ci"
echo "[ci-deploy] test from the CI host:   ssh -i <key> deploy@$(hostname -I 2>/dev/null | awk '{print $1}') status"
