#!/usr/bin/env bash
# identity-check/apply — prove a restored identity (WireGuard keys / SilverGUARD db+jwt) from a folder restore.
# Reads only under /srv/restore/. Outputs PUBLIC facts only: never private keys, never .env values.
#
# params:  {"mode":"wireguard","keys":{"wg":"/srv/restore/<id>/etc/wireguard/server_private.key",...}}
#      or  {"mode":"silverguard","envFile":"/srv/restore/<id>/opt/silverguard/.env","db":"/srv/restore/<id>/.../npm-net.db"}
# outputs: {"publicKeys":{name:<b64>|null}}  |  {"jwtKeyPresent":bool,"dbIntegrity":"ok"|"<line>","hostCount":int|null}
set -euo pipefail
P=$(cat)
die() { echo "ERROR: $*" >&2; exit 1; }
ROOT="${SSR_IDENTITY_ROOT:-}"   # tests only: prefix every path
PATH_RE='^/srv/restore/[A-Za-z0-9._-]+(/[A-Za-z0-9._@+-]+)*$'

# check_path <logical path>: refuse anything outside the restore tree, dot segments, symlinks.
check_path() {
  local p="$1" t="$ROOT$1" rp
  [[ "$p" =~ $PATH_RE ]] || die "refusing $p (not under /srv/restore/)"
  [[ "$p/" != *"/../"* && "$p/" != *"/./"* ]] || die "refusing $p (. or .. component)"
  if [ -L "$t" ]; then die "refusing $p: it is a symlink"; fi
  if [ -e "$t" ]; then
    rp=$(realpath -e -- "$t") || die "refusing $p: cannot resolve"
    [[ "$rp" == "$(realpath -m -- "$ROOT/srv/restore")"/* ]] || die "refusing $p: resolves outside /srv/restore/"
  fi
}

mode=$(jq -r '.mode // empty' <<<"$P")
case "$mode" in
wireguard)
  mapfile -t NAMES < <(jq -r '.keys // {} | keys[]' <<<"$P")
  [ "${#NAMES[@]}" -gt 0 ] || die "keys is required"
  command -v wg >/dev/null 2>&1 || die "wg not installed"
  res='{}'
  for n in "${NAMES[@]}"; do
    [[ "$n" =~ ^[A-Za-z0-9_]+$ ]] || die "bad key name"
    p=$(jq -r --arg n "$n" '.keys[$n] // empty' <<<"$P")
    [ -n "$p" ] || die "refusing empty path for $n"
    check_path "$p"
    t="$ROOT$p"
    if [ -f "$t" ]; then
      pub=$(wg pubkey < "$t" 2>/dev/null) || die "wg pubkey failed for $n"
      res=$(jq -c --arg n "$n" --arg v "$pub" '.[$n]=$v' <<<"$res")
    else
      res=$(jq -c --arg n "$n" '.[$n]=null' <<<"$res")
    fi
  done
  jq -n --argjson k "$res" '{publicKeys:$k}' > "$SSR_OUTPUTS"
  echo "identity-check: wireguard public keys derived for ${#NAMES[@]} key(s)"
  ;;
silverguard)
  env=$(jq -r '.envFile // empty' <<<"$P"); db=$(jq -r '.db // empty' <<<"$P")
  [ -n "$env" ] && [ -n "$db" ] || die "envFile and db are required"
  check_path "$env"; check_path "$db"
  jwt=false
  if [ -f "$ROOT$env" ] && grep -Eq '^[[:space:]]*(export[[:space:]]+)?SILVERGUARD_JWT_KEY=[[:space:]]*["'"'"']?[^[:space:]"'"'"']' "$ROOT$env"; then jwt=true; fi
  integrity="database missing"; hosts=null
  if [ -f "$ROOT$db" ]; then
    SRC=("$ROOT$db")
    for sfx in -wal -shm; do
      check_path "$db$sfx"
      [ -f "$ROOT$db$sfx" ] && SRC+=("$ROOT$db$sfx")
    done
    command -v sqlite3 >/dev/null 2>&1 || { DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends sqlite3 >/dev/null 2>&1 || die "could not install sqlite3"; }
    base="$ROOT/srv/restore"; mkdir -p "$base"
    tmp=$(mktemp -d "$base/.identity-check.XXXXXX")
    trap 'rm -rf -- "$tmp"' EXIT
    trap 'exit 130' INT; trap 'exit 143' TERM; trap 'exit 129' HUP
    cp -- "${SRC[@]}" "$tmp/" || die "could not copy the database"
    copy="$tmp/$(basename "$db")"
    SQ=(sqlite3 -batch -init /dev/null)
    integrity=$("${SQ[@]}" "$copy" "PRAGMA integrity_check" 2>&1 | head -n1) || true
    [ -n "$integrity" ] || integrity="no result from integrity_check"
    if [ "$("${SQ[@]}" "$copy" "select count(*) from sqlite_master where type='table' and name='proxy_host'" 2>/dev/null | head -n1)" = 1 ]; then
      n=$("${SQ[@]}" "$copy" "select count(*) from proxy_host" 2>/dev/null | head -n1) || true
      [[ "$n" =~ ^[0-9]+$ ]] && hosts=$n
    fi
    rm -rf -- "$tmp"; trap - EXIT INT TERM HUP
  fi
  jq -n --argjson j "$jwt" --arg i "$integrity" --argjson h "$hosts" '{jwtKeyPresent:$j,dbIntegrity:$i,hostCount:$h}' > "$SSR_OUTPUTS"
  echo "identity-check: silverguard jwtKeyPresent=$jwt dbIntegrity=$integrity hostCount=$hosts"
  ;;
*) die "mode must be wireguard or silverguard";;
esac
