#!/bin/bash
# socks-ensure-detached.sh — Long-term Plan B scheduler-layer detached wrapper (r13 / v19.5 host-61220 final)
# Addresses host rulings 61212 & 61220 + A87 61213/61219 (dKWkD) + A65 61200/61208/61215:
#   1. Launches missing loops inside own session (`setsid -f`) with stdin=/dev/null, log redirection,
#      and full close of inherited FDs > 2.
#   2. Post-spawn survival window (`SOCKS_START_SETTLE_SEC`, default `0.60s` >= `0.50s`):
#      declares `SPAWN_OK [START-OK]` ONLY if at window end the **exact same single PID** is still alive
#      (non-zombie `Z/X`, `kill -0`) AND `SID == PID` (`PGID == PID`); otherwise logs `ERROR [START-FAIL]`
#      to stderr (and `SOCKS_ENSURE_DETACHED_LOG` if set) and returns `rc=1`.
#   3. Fast O(candidates) discovery (`pgrep -f` C pre-filter + exact `/proc/<pid>/{stat,cmdline,cwd}` check)
#      + tight 5x0.03s (`0.15s`) exec-appearance budget:
#      - immediate `exit 7` failure path completes in `~0.35s` (`<< 2.0s` even on servers with thousands of processes!);
#      - delayed `sleep 0.30; exit 1` failure path completes in `~0.68s` (`<< 2.0s`);
#      - cold start of both healthy loops completes in `~0.68s` (`<< 3.0s`); warm check in `~0.03s`.
#   4. Per host ruling 61220 §4: pre-existing duplicate loops (`count > 1`) log `[WARN-DUPLICATE-LOOPS]`
#      with all PIDs without spawning duplicates or killing processes and return `0` by default
#      (set `SOCKS_STRICT_DUPLICATE_RC3=1` for `rc=3` alert mode).

set -euo pipefail

if [ -n "${SOCKS_SCRIPTS_DIR:-}" ]; then
  WS_DIR="$SOCKS_SCRIPTS_DIR"
elif [ -n "${SOCKS_WORKSPACE_DIR:-}" ]; then
  WS_DIR="$SOCKS_WORKSPACE_DIR"
else
  WS_DIR="$HOME/workspace"
fi
WS_REAL="$(readlink -f "$WS_DIR" 2>/dev/null || printf '%s' "$WS_DIR")"

LOCK_FILE="${SOCKS_ENSURE_LOCK:-${SOCKS_ENSURE_LOCK_FILE:-/tmp/socks-ensure-detached.$(id -u).lock}}"
DETACHED_LOG="${SOCKS_ENSURE_DETACHED_LOG:-}"
SOCKS_KEEP="${SOCKS_KEEP_SCRIPT:-$WS_REAL/socks-keep.sh}"
SOCKS90_KEEP="${SOCKS90_KEEP_SCRIPT:-$WS_REAL/socks90-keep.sh}"
SOCKS_KEEP_LOG="${SOCKS_KEEP_LOG:-/tmp/socks-keep.log}"
SOCKS90_KEEP_LOG="${SOCKS90_KEEP_LOG:-/tmp/socks90-keep.log}"
SETTLE_SEC="${SOCKS_START_SETTLE_SEC:-0.60}"

ts_hkt() {
  TZ="Asia/Hong_Kong" date "+%Y-%m-%d %H:%M:%S HKT"
}

log_info() {
  local msg="$*"
  printf '%s\n' "$msg"
  if [ -n "$DETACHED_LOG" ]; then
    mkdir -p "$(dirname "$DETACHED_LOG")" 2>/dev/null || true
    printf '%s\n' "$msg" >>"$DETACHED_LOG" 2>/dev/null || true
  fi
}

log_error() {
  local msg="$*"
  printf '%s\n' "$msg" >&2
  if [ -n "$DETACHED_LOG" ]; then
    mkdir -p "$(dirname "$DETACHED_LOG")" 2>/dev/null || true
    printf '%s\n' "$msg" >>"$DETACHED_LOG" 2>/dev/null || true
  fi
}

# Fail closed if LOCK_FILE cannot be opened/created; exit 0 ONLY on active concurrent flock contention.
if ! { exec 9>"$LOCK_FILE"; } 2>/dev/null; then
  log_error "$(ts_hkt) ERROR [LOCK-ERROR] cannot open lock file: $LOCK_FILE"
  exit 1
fi
if ! flock -n 9; then
  log_info "$(ts_hkt) [SKIP-LOCK] another socks-ensure-detached.sh instance holds $LOCK_FILE; exiting 0"
  exit 0
fi

# Print "<state> <ppid> <pgid> <sid>" for a live non-zombie PID, or return 1 if dead/zombie.
read_proc_ids() {
  local pid="$1" stat_raw="" rest="" st="" ppid="" pgid="" sid=""
  [ -r "/proc/$pid/stat" ] || return 1
  IFS= read -r stat_raw < "/proc/$pid/stat" 2>/dev/null || return 1
  [ -n "$stat_raw" ] || return 1
  rest="${stat_raw##*) }"
  set -- $rest
  st="${1:-}"; ppid="${2:-}"; pgid="${3:-}"; sid="${4:-}"
  case "$st" in
    ""|Z*|X*) return 1 ;;
  esac
  kill -0 "$pid" 2>/dev/null || return 1
  printf '%s %s %s %s\n' "$st" "$ppid" "$pgid" "$sid"
}

# Fast O(matching candidates) PID discovery:
#   Uses native C `pgrep -f "$target_base"` when available to avoid O(N_all_procs) bash globbing on large servers,
#   then verifies EVERY candidate against `/proc/<pid>/{stat,cmdline,cwd}` (zero COLUMNS truncation, zero zombie hits,
#   zero cross-directory contamination).
find_live_loop_pids() {
  local target_script="$1"
  local target_real target_base pid proc_dir stat_raw rest st tok match_ok is_dash_c cwd_real raw_pids
  target_real="$(readlink -f "$target_script" 2>/dev/null || printf '%s' "$target_script")"
  target_base="${target_real##*/}"

  if command -v pgrep >/dev/null 2>&1; then
    raw_pids="$(pgrep -f "$target_base" 2>/dev/null || true)"
  else
    raw_pids=""
    for proc_dir in /proc/[0-9]*; do
      raw_pids="$raw_pids ${proc_dir#/proc/}"
    done
  fi

  for pid in $raw_pids; do
    if [ "$pid" = "$$" ] || [ "$pid" = "${PPID:-0}" ]; then
      continue
    fi
    proc_dir="/proc/$pid"
    [ -r "$proc_dir/stat" ] && [ -r "$proc_dir/cmdline" ] || continue
    stat_raw=""
    IFS= read -r stat_raw < "$proc_dir/stat" 2>/dev/null || continue
    [ -n "$stat_raw" ] || continue
    rest="${stat_raw##*) }"
    st="${rest%% *}"
    case "$st" in
      ""|Z*|X*) continue ;;
    esac
    kill -0 "$pid" 2>/dev/null || continue

    match_ok=0
    is_dash_c=0
    while IFS= read -r -d '' tok; do
      if [ "$tok" = "-c" ]; then
        is_dash_c=1
        break
      fi
      if [ "$tok" = "$target_real" ] || [ "$tok" = "$target_script" ]; then
        match_ok=1
      elif [ "$tok" = "$target_base" ] || [ "$tok" = "./$target_base" ]; then
        cwd_real="$(readlink -f "$proc_dir/cwd" 2>/dev/null || printf '')"
        if [ "$cwd_real" = "$WS_REAL" ]; then
          match_ok=1
        fi
      fi
    done < "$proc_dir/cmdline" 2>/dev/null || true

    if [ "$is_dash_c" -eq 0 ] && [ "$match_ok" -eq 1 ]; then
      printf '%s\n' "$pid"
    fi
  done
}

readonly_check_socks90() {
  local s90="$1"
  if grep -Eq '^[[:space:]]*[^#]*ssh[[:space:]].*-L[[:space:]]*([0-9.]+:)?11090:' "$s90"; then
    log_error "$(ts_hkt) ERROR [FATAL-60564] $s90 contains forbidden '-L ... 11090:' static tunnel; refusing to start without modifying file"
    return 2
  fi
  if [ "${SOCKS_REQUIRE_SSH_D:-0}" = "1" ] && ! grep -Eq '^[[:space:]]*[^#]*ssh[[:space:]].*-D[[:space:]]*([0-9.]+:)?11090([[:space:]]|$)' "$s90"; then
    log_error "$(ts_hkt) ERROR [FATAL-11090-NO-SSH-D] $s90 lacks affirmative executable 'ssh ... -D ... 11090'"
    return 2
  fi
  return 0
}

REPLY_CAND_PID=""
REPLY_SPAWNED=0

prepare_or_launch_loop() {
  local label="$1"
  local script_path="$2"
  local log_path="$3"
  REPLY_CAND_PID=""
  REPLY_SPAWNED=0

  if [ ! -f "$script_path" ]; then
    log_error "$(ts_hkt) ERROR [MISSING] $label script not found at $script_path"
    return 1
  fi

  local live_pids live_count flat_pids
  live_pids="$(find_live_loop_pids "$script_path")"
  if [ -n "$live_pids" ]; then
    live_count="$(printf '%s\n' "$live_pids" | sed '/^$/d' | wc -l | tr -d ' ')"
    flat_pids="$(printf '%s' "$live_pids" | tr '\n' ' ' | sed 's/ $//')"
    if [ "$live_count" -gt 1 ]; then
      if [ "${SOCKS_STRICT_DUPLICATE_RC3:-0}" = "1" ]; then
        log_error "$(ts_hkt) ERROR [DUPLICATE-LOOPS] $label has $live_count live processes (pids: $flat_pids); strict mode returning rc=3"
        return 3
      fi
      log_info "$(ts_hkt) [WARN-DUPLICATE-LOOPS] $label already has $live_count live processes (pids: $flat_pids); not spawning new duplicate (host ruling 61220 §4)"
      return 0
    fi
    log_info "$(ts_hkt) [OK-ALIVE] $label already running (count=1 pid: $flat_pids)"
    return 0
  fi

  if [ "$label" = "socks90-keep" ]; then
    readonly_check_socks90 "$script_path" || return $?
  fi

  mkdir -p "$(dirname "$log_path")"

  setsid -f /bin/bash -c '
    for _fd in /proc/self/fd/*; do
      _fd="${_fd##*/}"
      case "$_fd" in
        0|1|2) ;;
        *) eval "exec ${_fd}>&-" 2>/dev/null || true ;;
      esac
    done
    if [ -x "$1" ]; then
      exec "$1"
    else
      exec /bin/bash "$1"
    fi
  ' _ "$script_path" </dev/null >>"$log_path" 2>&1

  # Tight 5 x 0.03s (0.15s max) exec-appearance budget so immediate-exit failures (`exit 7`) complete in ~0.35s << 2.0s!
  local attempt=0 new_pids="" cnt=0
  while [ "$attempt" -lt 5 ]; do
    new_pids="$(find_live_loop_pids "$script_path")"
    if [ -n "$new_pids" ]; then
      cnt="$(printf '%s\n' "$new_pids" | sed '/^$/d' | wc -l | tr -d ' ')"
      if [ "$cnt" -eq 1 ]; then
        REPLY_CAND_PID="$(printf '%s' "$new_pids" | tr -d ' \n')"
        REPLY_SPAWNED=1
        return 0
      fi
      log_error "$(ts_hkt) ERROR [START-FAIL] $label unexpected candidate PID count=$cnt ($new_pids)"
      return 1
    fi
    sleep 0.03
    attempt=$((attempt + 1))
  done

  log_error "$(ts_hkt) ERROR [START-FAIL] $label failed to start or exited immediately; check $log_path"
  return 1
}

verify_post_window_survival() {
  local label="$1"
  local script_path="$2"
  local cand_pid="$3"
  local log_path="$4"
  local post_pids proc_info st ppid pgid sid

  post_pids="$(find_live_loop_pids "$script_path" | tr -d ' \n' || true)"
  if [ "$post_pids" != "$cand_pid" ]; then
    log_error "$(ts_hkt) ERROR [START-FAIL] $label candidate pid=$cand_pid did not survive ${SETTLE_SEC}s window (post_pids='${post_pids:-none}'); check $log_path"
    return 1
  fi
  if ! proc_info="$(read_proc_ids "$cand_pid")"; then
    log_error "$(ts_hkt) ERROR [START-FAIL] $label candidate pid=$cand_pid became dead/zombie at end of ${SETTLE_SEC}s window; check $log_path"
    return 1
  fi
  set -- $proc_info
  st="$1"; ppid="$2"; pgid="$3"; sid="$4"
  if [ "$sid" != "$cand_pid" ] || [ "$pgid" != "$cand_pid" ]; then
    log_error "$(ts_hkt) ERROR [START-FAIL] $label pid=$cand_pid failed session isolation check (sid=$sid pgid=$pgid != pid=$cand_pid)"
    return 1
  fi
  log_info "$(ts_hkt) SPAWN_OK [START-OK] $label detached and survived ${SETTLE_SEC}s window (pid=$cand_pid sid=$sid pgid=$pgid ppid=$ppid)"
  return 0
}

rc=0
SPAWNED_1=0; CAND_1=""
SPAWNED_2=0; CAND_2=""

if prepare_or_launch_loop "socks-keep" "$SOCKS_KEEP" "$SOCKS_KEEP_LOG"; then
  SPAWNED_1="$REPLY_SPAWNED"; CAND_1="$REPLY_CAND_PID"
else
  rc=$?
fi

if prepare_or_launch_loop "socks90-keep" "$SOCKS90_KEEP" "$SOCKS90_KEEP_LOG"; then
  SPAWNED_2="$REPLY_SPAWNED"; CAND_2="$REPLY_CAND_PID"
else
  _rc2=$?
  [ "$rc" -eq 0 ] && rc="$_rc2"
fi

if [ "$SPAWNED_1" -eq 1 ] || [ "$SPAWNED_2" -eq 1 ]; then
  sleep "$SETTLE_SEC"
  if [ "$SPAWNED_1" -eq 1 ]; then
    verify_post_window_survival "socks-keep" "$SOCKS_KEEP" "$CAND_1" "$SOCKS_KEEP_LOG" || { [ "$rc" -eq 0 ] && rc=1; }
  fi
  if [ "$SPAWNED_2" -eq 1 ]; then
    verify_post_window_survival "socks90-keep" "$SOCKS90_KEEP" "$CAND_2" "$SOCKS90_KEEP_LOG" || { [ "$rc" -eq 0 ] && rc=1; }
  fi
fi

exec 9>&-
exit "$rc"
