#!/usr/bin/env bash
# KateRTX · pure BASH DNS lifeline · no python · no dig engine
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
XROOT="$(cd "$ROOT/.." && pwd)"
LL="$XROOT/RTXLayer/dns/lifeline.sh"
OUT="$XROOT/out/lifeline"
mkdir -p "$OUT"
cmd="${1:-status}"
shift || true

case "$cmd" in
  serve|run|start)
    if [[ -f "$OUT/lifeline.pid" ]]; then
      pid=$(cat "$OUT/lifeline.pid")
      if [[ -d "/proc/$pid" ]]; then
        echo "already running pid=$pid"
        exit 0
      fi
      rm -f "$OUT/lifeline.pid"
    fi
    nohup bash "$LL" serve >>"$OUT/lifeline.nohup.log" 2>&1 &
    echo $! >"$OUT/lifeline.pid"
    sleep 0.4
    echo "KateRTX lifeline BASH pid=$(cat "$OUT/lifeline.pid")"
    echo "resolve: $0 resolve biggrinrtx.com"
    ;;
  stop|learn|hops|status|resolve|lookup|get)
    exec bash "$LL" "$cmd" "$@"
    ;;
  *)
    echo "krtx-dns serve|stop|learn|hops|status|resolve [name]"
    exit 2
    ;;
esac
