#!/bin/bash
# C A T A L Y S T
# https://magister.ai/catalyst
# Copyright 2020-2026 Magister, LLC

# Run one foreground job in an owned group, optionally monitoring SSH stdin.

control=0
if [ "$1" = --control ]; then control=1; shift; fi
if [ "$#" -lt 1 ] || [ "$#" -gt 2 ]; then
  echo 'Usage: mc-nexus-run [--control] COMMAND [INTERRUPT_GRACE_SECONDS]' >&2
  exit 2
fi
grace=${2:-2}
case "$grace" in
  ''|*[!0-9]*) echo 'mc-nexus-run: invalid interrupt grace' >&2; exit 2 ;;
esac
if [ "${#grace}" -gt 2 ] || [ "$((10#$grace))" -gt 60 ]; then
  echo 'mc-nexus-run: interrupt grace must be between 0 and 60' >&2
  exit 2
fi
set -- "$1" "$((10#$grace))"

umask 077
work=$(mktemp -d "${TMPDIR:-/tmp}/nexus.XXXXXXXX") || exit 125
job=
watcher=
cancelled=0
cleanup(){
  trap '' INT TERM HUP
  if [ -n "$job" ]; then
    kill -KILL -- "-$job" 2>/dev/null || :
    wait "$job" 2>/dev/null || :
  fi
  if [ -n "$watcher" ]; then
    kill -KILL -- "-$watcher" 2>/dev/null || :
    wait "$watcher" 2>/dev/null || :
  fi
  rm -rf -- "$work"
}
trap cleanup EXIT
trap 'cancelled=1' INT TERM HUP
set -m
bash -c '
  trap : INT TERM HUP
  bash -c "$1" </dev/null
  result=$?
  if ! { printf "%s\n" "$result" > "$2/status.tmp" &&
         mv -- "$2/status.tmp" "$2/status"; }; then
    exit 125
  fi
  while :; do sleep 86400; done
' nexus-job "$1" "$work" </dev/null &
job=$!
if [ "$control" = 1 ]; then
  # A blocking reader avoids Bash 3.2's identical timeout and EOF status.
  # It keeps its group alive until cleanup, just like the command guardian.
  (
    trap : INT TERM HUP
    while IFS= read -r request; do
      if [ "$request" = cancel ]; then break; fi
    done
    : > "$work/cancel" || exit 125
    while :; do sleep 86400; done
  ) <&0 &
  watcher=$!
fi
set +m
running(){
  local current
  for current in $(jobs -pr); do
    if [ "$current" = "$1" ]; then return 0; fi
  done
  return 1
}
while [ ! -f "$work/status" ]; do
  if [ -f "$work/cancel" ]; then cancelled=1; fi
  if [ "$cancelled" = 1 ]; then break; fi
  if ! running "$job"; then
    echo 'mc-nexus: remote guardian exited without a status' >&2
    exit 125
  fi
  if [ -n "$watcher" ] && ! running "$watcher"; then
    cancelled=1
    continue
  fi
  sleep 0.05
done
if [ "$cancelled" = 1 ]; then
  kill -INT -- "-$job" 2>/dev/null || :
  sleep "$2"
  if [ ! -f "$work/status" ]; then
    kill -TERM -- "-$job" 2>/dev/null || :
    sleep "$2"
  fi
  exit 130
fi
IFS= read -r result < "$work/status"
case "$result" in
  ''|*[!0-9]*) echo 'mc-nexus: invalid remote status' >&2; exit 125 ;;
esac
exit "$result"
