#!/bin/bash
# NOQ Purser: SSH forced command for the box. Runs as the unprivileged gate user.
# A paired box's key line runs "purser-gate <box id>" and may ask exactly:
#   latest                          newest published generation id
#   rsync --server --sender ...     read-only rsync below generation/ (rrsync -ro)
#   ack <id> [tamam|uyari|supheli]  the box's verdict; writes ack/<id>
#   note <event>                    an alarm from the box (fixed alphabet); purser-source raises it
# The one-time pairing key (from "purser pair", ten minutes, once) runs "purser-gate --pair":
#   pair <box id> ssh-ed25519 <key> hands the box's key to "purser pair" and waits for its answer
# Everything else is refused and logged. The only configuration it reads is BASE.
set -euo pipefail
CONF=${PURSER_SOURCE_CONF:-/etc/purser/source.conf}
BASE=${PURSER_BASE:-}
if [ -z "$BASE" ] && [ -r "$CONF" ]; then
  BASE=$(sed -n 's/^BASE=//p' "$CONF" | tail -1 | tr -d "\"'")
fi
[[ $BASE =~ ^/[A-Za-z0-9._/-]+$ ]] || { logger -t purser-gate "BASE not configured"; exit 3; }
RRSYNC=${RRSYNC:-$(command -v rrsync || echo /usr/bin/rrsync)}
cmd=${SSH_ORIGINAL_COMMAND:-}
box=${1:-box}
id_re='^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}-[0-9]{2}Z$'
boxid_re='^[A-HJ-NP-Z2-9]{4}$'
contact() {   # remember when and what the box asked (for the out-of-window alert of purser-source watch)
  printf '%s %s %s\n' "$(date -u +%s)" "$1" "$box" > "$BASE/ack/.contact.tmp" 2>/dev/null && mv -f "$BASE/ack/.contact.tmp" "$BASE/ack/.contact" 2>/dev/null || true
}
refuse() { logger -t purser-gate "refused ($box): $(printf '%.80s' "$cmd" | tr -cd 'A-Za-z0-9 ._/-')"; exit 1; }

if [ "$box" = --pair ]; then
  read -r verb id kt key extra <<< "$cmd" || true
  [ "$verb" = pair ] && [[ $id =~ $boxid_re ]] && [ "$kt" = ssh-ed25519 ] && [[ $key =~ ^[A-Za-z0-9+/]{40,100}={0,2}$ ]] && [ -z "${extra:-}" ] || refuse
  ip=${SSH_CLIENT%% *}
  [[ $ip =~ ^[0-9]{1,3}(\.[0-9]{1,3}){3}$ ]] || refuse
  d=$BASE/pair
  [ -d "$d" ] || { echo "not pairing"; exit 1; }
  printf '%s %s %s %s\n' "$id" "$ip" "$kt" "$key" > "$d/request.tmp" && mv -f "$d/request.tmp" "$d/request"
  logger -t purser-gate "pairing request from $id at $ip"
  for _ in $(seq 1 60); do
    if [ -s "$d/result" ]; then cat "$d/result"; exit 0; fi
    sleep 0.5
  done
  echo "no answer from purser pair"; exit 1
fi
[[ $box =~ $boxid_re ]] || [ "$box" = box ] || refuse

case "$cmd" in
  latest)
    contact latest
    exec cat "$BASE/generation/LATEST" ;;
  "ack "*)
    read -r _ id verdict extra <<< "$cmd"
    verdict=${verdict:-tamam}
    if ! [[ $id =~ $id_re ]] || [ ! -d "$BASE/generation/$id" ] || [ -n "${extra:-}" ] || ! [[ $verdict =~ ^(tamam|uyari|supheli)$ ]]; then
      logger -t purser-gate "invalid ack"; exit 2
    fi
    contact ack
    printf '%s %s %s\n' "$verdict" "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$box" > "$BASE/ack/$id"
    logger -t purser-gate "ack $id $verdict ($box)" ;;
  "note "*)
    read -r _ ev extra <<< "$cmd"
    [[ $ev =~ ^[a-z_]{1,32}$ ]] && [ -z "${extra:-}" ] || refuse
    contact note
    printf '%s %s %s\n' "$(date -u +%s)" "$box" "$ev" >> "$BASE/ack/.notes"
    logger -t purser-gate "note $ev ($box)" ;;
  "rsync --server --sender "*)
    contact rsync
    exec "$RRSYNC" -ro "$BASE/generation" ;;
  *) refuse ;;
esac
