#!/usr/bin/env bash
# drill-wipe/apply — delete a drill server's restored data and secrets, and prove they are gone.
# Desk only calls this for drill instances on drill-marked servers; the role keeps its own allow-list
# so it can never be pointed at system paths. Runs as root (role-helper); synchronous, real exit code.
#
# params:  {"paths":["/srv/apt","/root/.gnupg","/root/.aptly.conf"]}
# outputs: {"deleted":[...],"absent":[...]}   (absent = already gone)
set -euo pipefail
P=$(cat)
die() { echo "ERROR: $*" >&2; exit 1; }
ROOT="${SSR_WIPE_ROOT:-}"   # tests only: prefix every path

ALLOW_RE='^(/srv/[A-Za-z0-9._-]+(/[A-Za-z0-9._-]+)*|/data/[A-Za-z0-9._-]+(/[A-Za-z0-9._-]+)*|/var/lib/silvershell-agent/compose/[a-z0-9][a-z0-9_-]{0,62}|/root/\.gnupg|/root/\.aptly\.conf)$'
mapfile -t PATHS < <(jq -r '.paths[]? // empty' <<<"$P")
[ "${#PATHS[@]}" -gt 0 ] || die "paths is required"
for p in "${PATHS[@]}"; do
  [[ "$p" =~ $ALLOW_RE ]] || die "refusing to wipe $p (not an allow-listed drill path)"
  [[ "$p/" != *"/../"* && "$p/" != *"/./"* ]] || die "refusing to wipe $p (. or .. component)"
  # restore copies are kept, except the throwaway folder-restore rebuild dirs
  if [[ "$p" =~ ^(/srv/restore/rebuild-[0-9a-f]{32})(/.+)$ ]]; then
    # sub-path: its parent must resolve inside the rebuild dir (no symlinked intermediate dirs)
    rb="${BASH_REMATCH[1]}"
    if [ -e "$ROOT$(dirname "$p")" ]; then
      rpar=$(realpath -e -- "$ROOT$(dirname "$p")") || die "refusing to wipe $p (cannot resolve parent)"
      rrb=$(realpath -m -- "$ROOT$rb")
      [[ "$rpar" == "$rrb" || "$rpar" == "$rrb"/* ]] || die "refusing to wipe $p (parent resolves outside the rebuild dir)"
    fi
  elif [[ ! "$p" =~ ^/srv/restore/rebuild-[0-9a-f]{32}$ ]]; then
    case "$p" in /srv/restore*) die "refusing to wipe $p (restore copies are kept)";; esac
  fi
done

deleted=(); absent=()
for p in "${PATHS[@]}"; do
  t="$ROOT$p"
  if [ -L "$t" ]; then die "refusing to wipe $p: it is a symlink"; fi
  if [ -e "$t" ]; then rm -rf --one-file-system -- "$t"; deleted+=("$p"); else absent+=("$p"); fi
  [ ! -e "$t" ] || die "$p still exists after wipe"
done

jq -n --argjson d "$(printf '%s\n' "${deleted[@]+"${deleted[@]}"}" | jq -R . | jq -s 'map(select(length>0))')" \
      --argjson a "$(printf '%s\n' "${absent[@]+"${absent[@]}"}" | jq -R . | jq -s 'map(select(length>0))')" \
      '{deleted:$d,absent:$a}' > "$SSR_OUTPUTS"
echo "drill-wipe: deleted ${#deleted[@]}, already absent ${#absent[@]}"
