#!/usr/bin/env bash
# hpcnav-run: run any command as a protected job (HPC Navigator, WP1.3).
#
#   hpcnav-run [--log FILE] [--done-marker FILE] [--exit zero|real] [--expected-hours H]
#              [--max-failures N] [--grace S] [--idle-minutes M [--shared-gpu]]
#              [--guard-dir DIR] -- COMMAND ...
#
# If Python 3.9 or later with the hpcnav-job package is in the image (or HPCNAV_PYTHON names
# one), this hands over to `python -m hpcnav_job.run`, which does everything below plus the run
# record. Otherwise this script does it in bash:
#
# - TERM, INT and HUP reach the command, and the wrapper waits for it to exit (so a checkpoint
#   handler can finish), then exits 143: the scheduler sees an interruption.
# - All output is copied to --log, on shared storage, so it outlives the pod.
# - --done-marker: if the file exists, do nothing; written only after a clean success.
# - After a normal end it exits 0 and logs the real code, so a scheduler that re-creates failed
#   pods does not loop; --exit real passes the real code on.
# - Crash-loop guard: after --max-failures failed starts in a row (default 3) it refuses to run
#   the command again and exits 0. Time cap: with --expected-hours H, the command gets 1.5 x H
#   hours plus any hours `hpcnav extend` writes to <guard dir>/extend_hours; then TERM, --grace
#   seconds (default 120), KILL. Idle guard: with --idle-minutes M, after the first 10 minutes,
#   the same TERM and KILL once the GPU is idle (nvidia-smi under 5 % busy) for M minutes. With
#   --shared-gpu (a fraction, whose busy figure is the whole GPU's, other jobs' included) it is
#   the command's own processes that must be idle: under 5 % of a core together, from /proc.
#   Each guard writes a job.guard event.
# - Samples: with a GPU, a job.metrics event each minute (HPCNAV_RUN_CHECK_S): nvidia-smi's
#   figures and, from /proc, the CPU the command's processes use (no command names).
#
# Events go to $HPCNAV_EVENTS_DIR/<workload>/<part>.jsonl; without HPCNAV_EVENTS_DIR there are
# none, and the crash-loop guard is off unless --guard-dir is given.
#
# Based on train_wrapper.sh from the onboarding guide (commit 50290a1). Bash 3.2 compatible.
# Set HPCNAV_RUN_BASH=1 to skip the hand-over (tests use it).
set -uo pipefail   # no -e: the command's failure is reported, not fatal to the wrapper

# --- Hand over to Python when it is there -------------------------------------------------------
if [ "${HPCNAV_RUN_BASH:-0}" != 1 ]; then
  for py in ${HPCNAV_PYTHON:-} python3 python; do
    if command -v "$py" >/dev/null 2>&1 &&
       "$py" -c 'import sys, hpcnav_job; sys.exit(sys.version_info < (3, 9))' >/dev/null 2>&1; then
      exec "$py" -m hpcnav_job.run "$@"
    fi
  done
fi

LOG="" MARKER="" EXIT_MODE=zero EXPECTED_H="" MAX_FAILURES=3 GRACE=120 GUARD_DIR=""
IDLE_MIN="" SHARED=0 IDLE_AFTER_S=${HPCNAV_RUN_IDLE_AFTER_S:-600}
FAILURE_WINDOW_S=7200 CHECK_EVERY=${HPCNAV_RUN_CHECK_S:-60} TEE_WAIT_S=${TEE_WAIT_S:-10}

say() { echo "[hpcnav-run] $(date -u +%Y-%m-%dT%H:%M:%SZ) $*"; }
die() { echo "[hpcnav-run] $*" >&2; exit 2; }
need() { [ "$2" -ge 2 ] || die "$1 needs a value"; }

while [ $# -gt 0 ]; do
  case "$1" in
    --log)            need "$1" $#; LOG=$2; shift 2 ;;
    --done-marker)    need "$1" $#; MARKER=$2; shift 2 ;;
    --exit)           need "$1" $#; EXIT_MODE=$2; shift 2 ;;
    --expected-hours) need "$1" $#; EXPECTED_H=$2; shift 2 ;;
    --max-failures)   need "$1" $#; MAX_FAILURES=$2; shift 2 ;;
    --grace)          need "$1" $#; GRACE=$2; shift 2 ;;
    --guard-dir)      need "$1" $#; GUARD_DIR=$2; shift 2 ;;
    --idle-minutes)   need "$1" $#; IDLE_MIN=$2; shift 2 ;;
    --shared-gpu)     SHARED=1; shift ;;
    --check-every)    need "$1" $#; CHECK_EVERY=$2; shift 2 ;;
    --no-record)      shift ;;
    -h|--help)        awk 'NR == 1 { next } /^#/ { sub(/^# ?/, ""); print; next } { exit }' "$0"; exit 0 ;;
    --)               shift; break ;;
    *)                die "unknown argument '$1'; put the command after --" ;;
  esac
done
[ $# -ge 1 ] || die "no command given; put it after --"
case "$EXIT_MODE" in zero|real) ;; *) die "--exit must be zero or real" ;; esac
case "$IDLE_MIN" in "") ;; *[!0-9.]*|.|*.*.*) die "--idle-minutes must be a number of minutes" ;; esac

# --- Who this job is (same rules as hpcnav_job.identity) ---------------------------------------
HOST=${HOSTNAME:-$(uname -n 2>/dev/null || echo job)}
WORKLOAD=${HPCNAV_WORKLOAD:-}
JOB_ID=${HPCNAV_JOB_ID:-}
PART=${HPCNAV_PART:-}
PART_KEY=pod
if [ -n "${SLURM_JOB_ID:-}" ]; then
  WORKLOAD=${WORKLOAD:-${SLURM_JOB_NAME:-$SLURM_JOB_ID}}; JOB_ID=${JOB_ID:-$SLURM_JOB_ID}
  PART=${PART:-$SLURM_JOB_ID${SLURM_STEP_ID:+.$SLURM_STEP_ID}}; PART_KEY=step
elif [ -n "${PBS_JOBID:-}" ]; then
  WORKLOAD=${WORKLOAD:-${PBS_JOBNAME:-$PBS_JOBID}}; JOB_ID=${JOB_ID:-$PBS_JOBID}; PART=${PART:-$PBS_JOBID}; PART_KEY=step
fi
[ -n "$WORKLOAD" ] || WORKLOAD=${RUNAI_JOB_NAME:-}
[ -n "$WORKLOAD" ] || WORKLOAD=$(printf '%s' "$HOST" | sed -E 's/-[0-9]+-[0-9]+$//')
HPCNAV_PROJECT=${HPCNAV_PROJECT:-${RUNAI_PROJECT:-}}
PART=${PART:-$HOST}
SITE=$(printf '%s' "${HPCNAV_SITE:-local}" | tr 'A-Z' 'a-z')
case "$SITE" in [a-z0-9]*) ;; *) SITE=local ;; esac
safe() { printf '%s' "$1" | sed 's/[^A-Za-z0-9._-]/_/g'; }
EVENTS_FILE=""
if [ -n "${HPCNAV_EVENTS_DIR:-}" ]; then
  JOB_DIR="$HPCNAV_EVENTS_DIR/$(safe "$WORKLOAD")"
  EVENTS_FILE="$JOB_DIR/$(safe "$PART").jsonl"
  [ -n "$GUARD_DIR" ] || GUARD_DIR="$JOB_DIR/guard"
fi

# --- Events: hpcnav.event/1, one line each ----------------------------------------------------
json_str() { printf '"%s"' "$(printf '%s' "$1" | sed -e 's/\\/\\\\/g' -e 's/"/\\"/g' | tr -d '\000-\037')"; }
json_opt() { if [ -n "$1" ]; then json_str "$1"; else printf null; fi; }
uuid7() {
  local ms hex r v
  ms=$(( $(date +%s) * 1000 ))
  hex=$(printf '%012x' "$ms")
  r=$(od -An -N10 -tx1 /dev/urandom | tr -d ' \n')
  v=$(printf '%x' $(( (0x${r:3:1} & 3) | 8 )))
  printf '%s-%s-7%s-%s%s-%s' "${hex:0:8}" "${hex:8:4}" "${r:0:3}" "$v" "${r:4:3}" "${r:8:12}"
}
WARNED_EVENTS=0
emit() {  # emit KIND SEVERITY PAYLOAD_JSON
  [ -n "$EVENTS_FILE" ] || return 0
  local subject line
  subject="{\"type\":\"workload\",\"name\":$(json_str "$WORKLOAD")"
  [ -z "$JOB_ID" ] || subject="$subject,\"id\":$(json_str "$JOB_ID")"
  subject="$subject,\"$PART_KEY\":$(json_str "$PART")}"
  line="{\"schema\":\"hpcnav.event/1\",\"id\":\"$(uuid7)\",\"time\":\"$(date -u +%Y-%m-%dT%H:%M:%SZ)\""
  line="$line,\"site\":$(json_str "$SITE"),\"source\":\"hpcnav-run\",\"kind\":\"$1\",\"severity\":\"$2\""
  [ -z "${HPCNAV_PROJECT:-}" ] || line="$line,\"project\":$(json_str "$HPCNAV_PROJECT")"
  [ -z "${HPCNAV_USER:-${USER:-}}" ] || line="$line,\"user\":$(json_str "${HPCNAV_USER:-${USER:-}}")"
  line="$line,\"subject\":$subject,\"payload\":$3}"
  if ! { mkdir -p "$(dirname "$EVENTS_FILE")" && printf '%s\n' "$line" >> "$EVENTS_FILE"; } 2>/dev/null; then
    [ "$WARNED_EVENTS" = 1 ] || echo "[hpcnav-run] cannot write events to $EVENTS_FILE; carrying on" >&2
    WARNED_EVENTS=1
  fi
}

# --- Log: a FIFO read by a background tee that ignores TERM, INT and HUP (from train_wrapper.sh)
TEE_PID="" FIFO_DIR=""
if [ -n "$LOG" ]; then
  mkdir -p "$(dirname "$LOG")" 2>/dev/null
  if : >> "$LOG" 2>/dev/null && FIFO_DIR=$(mktemp -d "${TMPDIR:-/tmp}/hpcnav-run.XXXXXX") \
     && mkfifo "$FIFO_DIR/out"; then
    ( trap '' TERM INT HUP; exec tee -a "$LOG" ) < "$FIFO_DIR/out" &
    TEE_PID=$!
    exec > "$FIFO_DIR/out" 2>&1
  else
    echo "[hpcnav-run] cannot write --log $LOG; logging to stdout only" >&2
  fi
fi
finish() {
  [ -z "${WATCH_PID:-}" ] || kill "$WATCH_PID" 2>/dev/null
  [ -z "${SAMPLE_PID:-}" ] || kill "$SAMPLE_PID" 2>/dev/null
  if [ -n "$TEE_PID" ]; then
    exec >&- 2>&-
    local waited=0
    while kill -0 "$TEE_PID" 2>/dev/null && [ "$waited" -lt $((TEE_WAIT_S * 10)) ]; do
      sleep 0.1 2>/dev/null || sleep 1; waited=$((waited + 1))
    done
    if kill -0 "$TEE_PID" 2>/dev/null; then kill -KILL "$TEE_PID" 2>/dev/null; fi
    wait "$TEE_PID" 2>/dev/null
    rm -rf "$FIFO_DIR"
  fi
  exit "$1"
}

if [ -n "$MARKER" ] && [ -e "$MARKER" ]; then
  say "done-marker $MARKER exists; nothing to do"
  finish 0
fi

# --- Crash-loop guard (same rules as hpcnav_job.guards) -----------------------------------------
if [ -n "$GUARD_DIR" ]; then
  mkdir -p "$GUARD_DIR" 2>/dev/null
  failed=$(awk -v window="$FAILURE_WINDOW_S" '
    $2 == "start" { n++; t[n] = $1; out[n] = "" }
    $2 == "end" && n > 0 && out[n] == "" { out[n] = ($3 == "" ? "?" : $3) }
    END {
      c = 0; later = ""
      for (i = n; i >= 1; i--) {
        if (later != "" && later - t[i] > window) break
        o = out[i]
        if (o == "" || o ~ /^-?[0-9]+$/ && o != "0") { c++; later = t[i]; continue }
        break
      }
      print c
    }' "$GUARD_DIR/attempts" 2>/dev/null || echo 0)
  if [ "${failed:-0}" -ge "$MAX_FAILURES" ]; then
    say "crash-loop guard: the last $failed starts failed; not starting again. Read the log, fix the cause, then resubmit under a new name (or remove $GUARD_DIR/attempts)"
    emit job.guard warning "{\"guard\":\"crash_loop\",\"limit\":$MAX_FAILURES,\"observed\":$failed,\"action\":\"stopped\"}"
    emit job.exit info '{"exit_code":null,"signal":null,"wrapped_exit":0}'
    finish 0
  fi
  echo "$(date +%s).000 start" >> "$GUARD_DIR/attempts"
fi

GOT_SIG="" CHILD=""
on_signal() {
  GOT_SIG=$1
  say "$1 received; forwarding it to the command${CHILD:+ (PID $CHILD)}"
  if [ -n "$CHILD" ]; then kill -s "$1" "$CHILD" 2>/dev/null; fi
}
trap 'on_signal TERM' TERM
trap 'on_signal INT' INT
trap 'on_signal HUP' HUP

say "start on $HOST ($WORKLOAD $PART): $*"
set -m
"$@" &
CHILD=$!
set +m
if [ -n "$GOT_SIG" ]; then kill -s "$GOT_SIG" "$CHILD" 2>/dev/null; fi

# --- Guards: watchers for the time cap and the idle GPU; the first to fire writes GUARD_FLAG -------
GUARD_FLAG=$(mktemp "${TMPDIR:-/tmp}/hpcnav-guard.XXXXXX"); rm -f "$GUARD_FLAG"
fire() {  # fire GUARD LIMIT OBSERVED WHY...: TERM so it can save, then KILL after the grace
  [ -s "$GUARD_FLAG" ] && return
  echo "$1 $2 $3" > "$GUARD_FLAG"
  local g=$1; shift 3
  say "$g guard fired ($*); sending TERM so it can save"
  kill -TERM "$CHILD" 2>/dev/null
  waited=0
  while kill -0 "$CHILD" 2>/dev/null && [ "$waited" -lt "$GRACE" ]; do sleep 1; waited=$((waited + 1)); done
  if kill -0 "$CHILD" 2>/dev/null; then say "the command did not stop within ${GRACE}s; killing it"; kill -KILL "$CHILD" 2>/dev/null; fi
}
WATCH_PID=""
if [ -n "$EXPECTED_H" ]; then
  (
    trap - TERM INT HUP
    start=$(date +%s)
    while kill -0 "$CHILD" 2>/dev/null; do
      sleep "$CHECK_EVERY"
      extra=$(cat "$GUARD_DIR/extend_hours" 2>/dev/null || echo 0)
      cap=$(awk -v h="$EXPECTED_H" -v e="${extra:-0}" 'BEGIN { if (e !~ /^[0-9.]+$/) e = 0; printf "%d", (h * 1.5 + e) * 3600 }')
      now=$(date +%s)
      if [ $((now - start)) -gt "$cap" ]; then
        fire time_cap $(awk -v c="$cap" -v o=$((now - start)) 'BEGIN { printf "%.3f %.3f cap ", c / 3600, o / 3600; if (c < 60) printf "%d s", c; else printf "%g min", int(c / 6 + 0.5) / 10 }')
        exit 0
      fi
    done
  ) &
  WATCH_PID=$!
fi
# Samples: each CHECK_EVERY, one nvidia-smi and one /proc reading, written as job.metrics and
# judged by the idle guard. A shared GPU's busy figure is the whole GPU's, so there the guard
# judges the CPU of the command and everything it started
gpu_read() {  # "BUSY PAYLOAD" over the GPUs nvidia-smi sees; nothing without
  nvidia-smi --query-gpu=utilization.gpu,memory.used,memory.total,power.draw --format=csv,noheader,nounits 2>/dev/null |
    awk -F, '$1 ~ /^ *[0-9.]+ *$/ { n++; u += $1; m += $2; t += $3; if ($4 ~ /[0-9]/) { p += $4; w = 1 } }
      END { if (!n) exit; u /= n; printf "%.1f \"gpu_util_pct\":%.1f,\"gpu_mem_used_bytes\":%.0f,\"gpu_mem_total_bytes\":%.0f,%s\"gpu_count\":%d", u, u, m * 1048576, t * 1048576, w ? sprintf("\"power_w\":%.1f,", p) : "", n }'
}
CPU_ST=$GUARD_FLAG.cpu HZ=$(getconf CLK_TCK 2>/dev/null || echo 100)
cpu_read() {  # cpu_read SECONDS: "BUSY PAYLOAD" for the command's processes since the last call
  cat /proc/[0-9]*/stat 2>/dev/null | awk -v root="$CHILD" -v st="$CPU_ST" -v s="$1" -v hz="$HZ" '
    FILENAME == st { o[$1] = $2; next }
    { r = $0; sub(/^.*\) /, "", r); split(r, f, " "); pp[$1] = f[2]; t[$1] = f[12] + f[13] }
    END { if (!(root in t)) exit
      for (p in t) { q = p; n = 0; while (q != root && (q in pp) && n++ < 64) q = pp[q]
        if (q == root) { a += t[p]; print p, t[p] > st; v[++k] = t[p] > o[p] ? t[p] - o[p] : 0 } }
      print "T", a > st
      if (s <= 0 || !("T" in o)) { print "- "; exit }
      for (i = 1; i <= k && i <= 8; i++) { b = i; for (j = i + 1; j <= k; j++) if (v[j] > v[b]) b = j
        x = v[b]; v[b] = v[i]; top = top (i > 1 ? "," : "") sprintf("%.1f", x * 100 / hz / s) }
      c = (a > o["T"] ? a - o["T"] : 0) * 100 / hz / s
      printf "%.1f \"cpu_cores_used\":%.2f,\"cpu_top_pct\":[%s],", c, c / 100, top }' "$CPU_ST" -
}
: > "$CPU_ST"
gpu=$(gpu_read) cpu=$(cpu_read 0) metrics="" SAMPLE_PID=""
[ -z "$EVENTS_FILE" ] || [ -z "$gpu" ] || metrics=1
if [ -n "$IDLE_MIN" ]; then
  if [ "$SHARED" = 1 ]; then what="the job's processes" reading=$cpu
  else what="the GPU" reading=$gpu; fi
  [ -n "$reading" ] || { say "can't read $what (nvidia-smi or /proc), so the idle guard is off"; IDLE_MIN=""; }
fi
if [ -n "$IDLE_MIN$metrics" ]; then
  (
    trap - TERM INT HUP
    start=$(date +%s) since="" last=$start w=$start
    while kill -0 "$CHILD" 2>/dev/null; do
      sleep "$CHECK_EVERY"
      now=$(date +%s) gpu=$(gpu_read) cpu=""
      if [ "$now" -gt "$last" ]; then cpu=$(cpu_read $((now - last))); last=$now; fi
      if [ -n "$metrics" ] && [ -n "$gpu" ]; then
        emit job.metrics info "{${gpu#* },${cpu#* }\"window_s\":$((now - w)),\"origin\":\"nvidia-smi\"}"; w=$now
      fi
      if [ "$SHARED" = 1 ]; then busy=${cpu%% *}; else busy=${gpu%% *}; fi
      [ "$busy" != - ] || busy=""
      [ -n "$IDLE_MIN" ] && [ -n "$busy" ] && [ $((now - start)) -ge "$IDLE_AFTER_S" ] || continue
      if awk -v b="$busy" 'BEGIN { exit !(b >= 5) }'; then since=""; continue; fi
      since=${since:-$now}
      idle=$(awk -v s=$((now - since)) -v m="$IDLE_MIN" 'BEGIN { printf "%g %g", m, s / 60; exit !(s / 60 >= m) }') || continue
      fire idle $idle "$what idle for ${idle#* } min"
      exit 0
    done
  ) &
  SAMPLE_PID=$!
fi

rc=0
while :; do
  wait "$CHILD"; rc=$?
  kill -0 "$CHILD" 2>/dev/null || break
done
if [ -n "$GOT_SIG" ]; then wait "$CHILD" 2>/dev/null; r=$?; [ "$r" -eq 127 ] || rc=$r; fi
[ -z "$WATCH_PID" ] || { kill "$WATCH_PID" 2>/dev/null; wait "$WATCH_PID" 2>/dev/null; WATCH_PID=""; }
[ -z "$SAMPLE_PID" ] || { kill "$SAMPLE_PID" 2>/dev/null; wait "$SAMPLE_PID" 2>/dev/null; SAMPLE_PID=""; }
rm -f "$CPU_ST"

if [ -n "$GOT_SIG" ]; then
  [ -z "$GUARD_DIR" ] || echo "$(date +%s).000 end sig-$GOT_SIG" >> "$GUARD_DIR/attempts"
  say "exit $rc ($GOT_SIG received: exiting 143 so the scheduler sees an interruption)"
  emit job.exit notice "{\"exit_code\":$rc,\"signal\":\"$GOT_SIG\",\"wrapped_exit\":143}"
  finish 143
fi
if [ -s "$GUARD_FLAG" ]; then
  read -r guard limit observed < "$GUARD_FLAG"; rm -f "$GUARD_FLAG"
  action=stopped
  case $rc in 0|143) action=checkpointed_and_stopped ;; esac
  [ -z "$GUARD_DIR" ] || echo "$(date +%s).000 end guard" >> "$GUARD_DIR/attempts"
  emit job.guard warning "{\"guard\":\"$guard\",\"limit\":$limit,\"observed\":$observed,\"action\":\"$action\"}"
  emit job.exit warning "{\"exit_code\":$rc,\"signal\":\"TERM\",\"wrapped_exit\":0}"
  say "exit $rc after the $guard guard; exiting 0 so the job is not restarted"
  finish 0
fi
rm -f "$GUARD_FLAG"
[ -z "$GUARD_DIR" ] || echo "$(date +%s).000 end $rc" >> "$GUARD_DIR/attempts"

say "exit $rc"
if [ "$rc" -eq 0 ] && [ -n "$MARKER" ]; then
  mkdir -p "$(dirname "$MARKER")" 2>/dev/null
  if printf 'completed %s: %s\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$*" > "$MARKER.tmp.$$" && mv "$MARKER.tmp.$$" "$MARKER"; then
    say "wrote done-marker $MARKER"
  fi
fi
wrapped=0
[ "$EXIT_MODE" = real ] && wrapped=$rc
sev=info; [ "$rc" -eq 0 ] || sev=warning
emit job.exit "$sev" "{\"exit_code\":$rc,\"signal\":null,\"wrapped_exit\":$wrapped}"
if [ "$rc" -ne 0 ] && [ "$wrapped" -eq 0 ]; then
  say "exiting 0 (--exit zero) so a scheduler that re-creates failed pods does not loop; the real code is $rc, above"
fi
finish "$wrapped"
