#!/bin/bash
# Privileged guard: nft apply, persistent state, restricted sudo surface.
set -euo pipefail
action="${1:-}"
table='inet lumen_guard'
state_dir='/var/lib/meeting-recorder-guard'
state_file="$state_dir/restricted"
config_dir='/etc/meeting-recorder-guard'
hosts_env="$config_dir/hosts.env"
release_token="$config_dir/release.token"
guard_http="${LUMEN_GUARD_HTTP:-http://127.0.0.1:17840}"

usage() {
  echo "usage: $0 nft-apply|nft-clear|status" >&2
  exit 2
}

require_guardd() {
  if [[ "${LUMEN_GUARDD:-}" != "1" ]]; then
    echo 'internal nft action requires guardd' >&2
    exit 1
  fi
}

require_root() {
  if [[ $(id -u) != 0 ]]; then
    echo 'lumen-guard-helper must run as root' >&2
    exit 1
  fi
}

load_hosts() {
  if [[ -f "$hosts_env" ]]; then
    while IFS= read -r line || [[ -n "$line" ]]; do
      line="${line%%#*}"
      line="$(printf '%s' "$line" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')"
      [[ -z "$line" ]] && continue
      key="${line%%=*}"
      val="${line#*=}"
      key="$(printf '%s' "$key" | sed -e 's/[[:space:]]*$//')"
      val="$(printf '%s' "$val" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')"
      case "$key" in
        LUMEN_GUARD_CRM_HOST) [[ -z "${LUMEN_GUARD_CRM_HOST:-}" ]] && LUMEN_GUARD_CRM_HOST="$val" ;;
        LUMEN_GUARD_FEED_HOST) [[ -z "${LUMEN_GUARD_FEED_HOST:-}" ]] && LUMEN_GUARD_FEED_HOST="$val" ;;
        LUMEN_GUARD_CONTROL_HOST) [[ -z "${LUMEN_GUARD_CONTROL_HOST:-}" ]] && LUMEN_GUARD_CONTROL_HOST="$val" ;;
      esac
    done <"$hosts_env"
  fi
  crm="${LUMEN_GUARD_CRM_HOST:-crm.elitesochi.com}"
  feed="${LUMEN_GUARD_FEED_HOST:-}"
  control="${LUMEN_GUARD_CONTROL_HOST:-}"
}

resolve_v4() {
  local host=$1 ip
  ip="$(getent ahostsv4 "$host" 2>/dev/null | awk '{print $1; exit}')" || true
  printf '%s' "$ip"
}

allow_host_rules() {
  local label=$1 host=$2
  local ip
  ip=$(resolve_v4 "$host")
  if [[ -z "$ip" ]]; then
    echo "warning: cannot resolve $label ($host)" >&2
    return 0
  fi
  cat <<RULES
    ip daddr $ip tcp dport { 80, 443 } accept
    ip daddr $ip udp dport { 80, 443 } accept
RULES
}

collect_nameservers() {
  local f
  for f in /etc/resolv.conf /run/systemd/resolve/resolv.conf; do
    [[ -f "$f" ]] || continue
    grep -E '^[[:space:]]*nameserver[[:space:]]+' "$f" 2>/dev/null | awk '{print $2}' | grep -E '^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$' || true
  done | awk '!seen[$0]++'
}

dns_rules() {
  local ns
  while read -r ns; do
    [[ -z "$ns" ]] && continue
    printf '    ip daddr %s udp dport 53 accept\n' "$ns"
    printf '    ip daddr %s tcp dport 53 accept\n' "$ns"
  done < <(collect_nameservers)
}

apply_nft() {
  require_root
  require_guardd
  load_hosts
  command -v nft >/dev/null || { echo 'nftables not installed' >&2; exit 1; }
  local rules extra dns
  extra=""
  crm_ip=$(resolve_v4 "$crm")
  if [[ -n "$crm_ip" ]]; then
    extra+="    ip daddr $crm_ip tcp dport { 80, 443 } accept
"
  else
    echo "warning: cannot resolve CRM host $crm for nft allowlist" >&2
  fi
  proxy_uid=$(getent passwd lumen-guard 2>/dev/null | awk -F: '{print $3}') || proxy_uid=""
  if [[ -z "$proxy_uid" ]]; then
    echo "warning: lumen-guard user missing; CRM proxy service may fail" >&2
  fi
  [[ -n "$feed" ]] && extra+="$(allow_host_rules FEED "$feed")"$'\n'
  [[ -n "$control" ]] && extra+="$(allow_host_rules CONTROL "$control")"$'\n'
  dns="$(dns_rules)"
  rules="table $table {
  chain output {
    type filter hook output priority 0; policy drop;
    ip daddr 127.0.0.0/8 accept
    ip6 daddr ::1 accept
$dns
$extra
  }
}"
  # Replace in a single nft transaction so restore and repeated locks work.
  if nft list table $table >/dev/null 2>&1; then
    rules=$'delete table inet lumen_guard\n'"$rules"
  elif ! nft list tables >/dev/null; then
    echo 'cannot inspect nft tables' >&2
    return 1
  fi
  if ! nft -f /dev/stdin <<<"$rules"; then
    echo 'nft apply failed' >&2
    exit 1
  fi
}

clear_nft() {
  require_root
  require_guardd
  command -v nft >/dev/null || { echo 'nftables not installed' >&2; exit 1; }
  if nft list table $table >/dev/null 2>&1; then
    nft delete table $table
  elif ! nft list tables >/dev/null; then
    echo 'cannot inspect nft tables' >&2
    return 1
  fi
}

case "$action" in
  nft-apply) apply_nft ;;
  nft-clear) clear_nft ;;
  status)
    if nft list table $table >/dev/null 2>&1; then
      echo active
      exit 0
    fi
    echo inactive
    ;;
  *) usage ;;
esac
