#!/usr/bin/env bash
# grok-orphan-kill · free · auto-clean Grok field orphans
# Kills: stray http.server / rtx_pass / rtx_glx / xdg-open · NOT bgrtx-datacenter.service
# Law: xdg-open = virus class on this desk (never auto-launch browsers)
# Log: ~/.local/state/grok-orphan-kill.log
set -u

LOG="${GROK_ORPHAN_LOG:-}"
if [[ -z "$LOG" ]]; then
  if [[ "$(id -u)" -eq 0 ]] && [[ -w /var/log ]]; then
    LOG=/var/log/grok-orphan-kill.log
  else
    mkdir -p "${XDG_STATE_HOME:-$HOME/.local/state}" 2>/dev/null || true
    LOG="${XDG_STATE_HOME:-$HOME/.local/state}/grok-orphan-kill.log"
  fi
fi

ts() { date -Iseconds 2>/dev/null || date; }
say() { echo "[$(ts)] $*" | tee -a "$LOG" 2>/dev/null || echo "[$(ts)] $*"; }

SELF=$$
PARENT=${PPID:-0}
killed=0

# MainPID of real unit (if running)
DC_MAIN=""
if command -v systemctl >/dev/null 2>&1; then
  DC_MAIN=$(systemctl show -p MainPID --value bgrtx-datacenter.service 2>/dev/null || true)
fi
[[ "$DC_MAIN" == "0" ]] && DC_MAIN=""

is_datacenter_unit() {
  local pid=$1
  [[ -d /proc/$pid ]] || return 1
  [[ -n "$DC_MAIN" && "$pid" == "$DC_MAIN" ]] && return 0
  if [[ -r /proc/$pid/cgroup ]] && grep -q 'bgrtx-datacenter' /proc/$pid/cgroup 2>/dev/null; then
    return 0
  fi
  if [[ -r /proc/$pid/environ ]]; then
    if tr '\0' '\n' </proc/$pid/environ 2>/dev/null | grep -qE '^(BGRTX_DATACENTER|BGRTX_KEEP)=1$'; then
      return 0
    fi
  fi
  if [[ -n "$DC_MAIN" && -r /proc/$pid/status ]]; then
    local pp
    pp=$(awk '/^PPid:/{print $2}' /proc/$pid/status 2>/dev/null || true)
    [[ "$pp" == "$DC_MAIN" ]] && return 0
  fi
  return 1
}

is_protected() {
  local pid=$1
  [[ "$pid" -eq 1 ]] && return 0
  [[ "$pid" -eq "$SELF" ]] && return 0
  [[ "$pid" -eq "$PARENT" ]] && return 0
  is_datacenter_unit "$pid" && return 0
  local cmd
  cmd=$(tr '\0' ' ' </proc/"$pid"/cmdline 2>/dev/null || true)
  case "$cmd" in
    *systemd*|*picom*|*Xorg*|*lxqt*|*sshd*|*dbus*|*grok-orphan-kill*) return 0 ;;
  esac
  return 1
}

kill_pid() {
  local pid=$1 reason=$2
  is_protected "$pid" && return 0
  if kill -0 "$pid" 2>/dev/null; then
    local cmd
    cmd=$(tr '\0' ' ' </proc/"$pid"/cmdline 2>/dev/null | cut -c1-160)
    if kill -TERM "$pid" 2>/dev/null; then
      sleep 0.15
      kill -KILL "$pid" 2>/dev/null || true
      say "KILL $pid · $reason · $cmd"
      killed=$((killed + 1))
    fi
  fi
}

is_real_target() {
  local pid=$1
  local comm cmd exe
  [[ -d /proc/"$pid" ]] || return 1
  is_datacenter_unit "$pid" && return 1
  comm=$(cat /proc/"$pid"/comm 2>/dev/null || echo "")
  cmd=$(tr '\0' ' ' <"/proc/$pid/cmdline" 2>/dev/null || true)
  exe=$(readlink -f /proc/"$pid"/exe 2>/dev/null || true)
  [[ -n "$cmd" || -n "$comm" ]] || return 1
  [[ "$cmd" == *grok-orphan-kill* ]] && return 1
  [[ "$cmd" == *systemctl* ]] && return 1
  [[ "$cmd" == *bgrtx-datacenter-serve* ]] && return 1
  if [[ "$comm" == bash || "$comm" == sh ]]; then
    return 1
  fi
  # stray python http.server on our ports (NOT unit)
  if [[ "$comm" == python* ]]; then
    [[ "$cmd" == *"-m http.server"* ]] || return 1
    [[ "$cmd" == *8766* || "$cmd" == *8765* || "$cmd" == *8877* ]] || return 1
    return 0
  fi
  if [[ "$comm" == rtx_pass || "$comm" == rtx_glx ]]; then
    return 0
  fi
  if [[ "$exe" == *"/rtx_pass" || "$exe" == *"/rtx_glx" ]]; then
    return 0
  fi
  # xdg-open = virus class · auto browser launch banned
  if [[ "$comm" == xdg-open || "$cmd" == *xdg-open* ]]; then
    return 0
  fi
  if [[ "$exe" == *"/xdg-open" ]]; then
    return 0
  fi
  return 1
}

say "scan start · DC_MAIN=${DC_MAIN:-none}"

while read -r pid; do
  [[ -z "$pid" ]] && continue
  [[ "$pid" -eq "$SELF" ]] && continue
  is_real_target "$pid" || continue
  kill_pid "$pid" "field-orphan"
done < <(pgrep -u default 2>/dev/null || pgrep -u "$(id -un)" 2>/dev/null || true)

while read -r pid ppid; do
  [[ -z "$pid" ]] && continue
  [[ "$ppid" != "1" ]] && continue
  is_datacenter_unit "$pid" && continue
  cmd=$(tr '\0' ' ' </proc/"$pid"/cmdline 2>/dev/null || true)
  case "$cmd" in
    *http.server*|*rtx_pass*|*rtx_glx*|*xdg-open*)
      is_real_target "$pid" && kill_pid "$pid" "PPID=1 orphan"
      ;;
  esac
done < <(ps -eo pid=,ppid= 2>/dev/null)


# port sweep · skip if unit owns the port
for port in 8766 8765 8877; do
  if [[ "$port" == "8766" ]] && systemctl is-active --quiet bgrtx-datacenter.service 2>/dev/null; then
    continue
  fi
  if command -v fuser >/dev/null 2>&1; then
    while read -r pid; do
      [[ -z "$pid" ]] && continue
      is_datacenter_unit "$pid" && continue
      is_real_target "$pid" && kill_pid "$pid" "port:$port"
    done < <(fuser "${port}/tcp" 2>/dev/null | tr ' ' '\n' | grep -E '^[0-9]+$' || true)
  fi
done

zcount=$(ps -eo stat= 2>/dev/null | grep -c '^Z' || true)
if [[ "${zcount:-0}" -gt 0 ]]; then
  say "NOTE zombies=$zcount"
fi
say "done · killed=$killed · protected unit=bgrtx-datacenter"
exit 0
