#!/usr/bin/env bash
#
# paas-ci-ssh — forced command for the CI key in /home/deploy/.ssh/authorized_keys
# (installed by infra/setup-ci-deploy.sh):
#
#   restrict,command="/usr/local/bin/paas-ci-ssh" ssh-ed25519 AAAA… jenkins-platform
#
# The Jenkins job runs   tar czf - . | ssh deploy@<host> deploy <commit> [<message>]
# and this wrapper only ever forwards to the exact-command sudoers entry for
# /usr/local/sbin/paas-self-deploy — the CI key cannot open a shell, run
# `paas`, or touch anything else on the box.

set -euo pipefail
read -r -a words <<<"${SSH_ORIGINAL_COMMAND:-}"
sub="${words[0]:-}"
case "$sub" in
deploy)
    commit="${words[1]:-unknown}"
    [[ "$commit" =~ ^[A-Za-z0-9._/-]{1,64}$ ]] || { echo "bad commit id" >&2; exit 2; }
    msg="${words[*]:2}"
    exec sudo -n /usr/local/sbin/paas-self-deploy deploy "$commit" "${msg:0:200}"
    ;;
verify|status|rollback)
    exec sudo -n /usr/local/sbin/paas-self-deploy "$sub"
    ;;
*)
    echo "paas-ci-ssh: only 'deploy <commit> [msg]', 'verify', 'status', 'rollback' are allowed" >&2
    exit 2
    ;;
esac
