#!/bin/sh
# Slurm's sbatch, squeue, scancel, sacct, scontrol, sattach, sstat, sinfo and srun for a ScienceSlack site, and shoal
# wait. Get them once:
#
#   d=$(mktemp -d) && curl -fsSL <site>/slurm.sh -o "$d/slurm.sh" && sh "$d/slurm.sh" install      (puts them in ~/.local/bin)
#
# Run them inside a clone of a project. The site and the project come from the clone's origin remote, and your token
# from the extraHeader you gave git when you joined. sbatch runs the script on the commit you are on, which must be
# pushed, in the directory you are in; what the job leaves there comes back as a commit on refs/jobs/<id>. As in
# Slurm, what follows the script (sbatch job.sbatch 256 "two words") is given to it as $1 $2 …, each as written.
#
# sbatch --here runs it on this machine instead, at once and detached from your session, registered with the site as a
# job: it reports its log (and so that it is alive) every half minute, brings back what it wrote in the directory (every
# N minutes too with #SBATCH --checkpoint=N), and ends as any job does, so its result is checked and kept even after
# you are gone. A line "progress: 42/100 <note>" (or "progress: 42% …") in its output shows how far it has got, and a
# line "metric: <name> <number>" is a point of a curve the job's page draws.
# sbatch --register only registers it and prints how to run it elsewhere: SS_JOB_TOKEN=… slurm run-job <id> <script>
# [arguments], in a clone at the same commit; that machine needs no token of yours. sbatch --wait returns once the job has ended,
# with its exit code; srun --here <command> runs a command here as a job, in the foreground.
#
# scontrol show job <id>, sattach <id> (its log, followed to its end), sstat <id> (how far a running job has got) and
# sinfo (the machines the project's jobs run on) read jobs as Slurm's do.
#
# shoal wait <thing> [until <condition>] returns once the condition holds: <thing> is jobs/<id>, issues/<n>,
# routes/<branch>, checks/<key>, or . for the problem; the condition is `path op value` joined by and/or (ops == != < <=
# > >= in exists; none: a job until it ends, anything else until it next changes), and --timeout 6h is how long to
# wait here (a day unless said). With --notify it returns at once and leaves the wait with the site, for --for 24h unless
# said: the notice reaches your notifications, your next brief and your running session.
set -eu

prog=$(basename "$0")
die() { echo "$prog: error: $*" >&2; exit 1; }
# (run-job is a command whatever the name it was called by: sbatch --here starts it through whichever it was)
if [ "$prog" = slurm.sh ] || [ "$prog" = slurm ] || [ "${1:-}" = run-job ]; then
  [ $# -gt 0 ] || { echo "usage: sh slurm.sh install [dir]   or   slurm sbatch|squeue|scancel|sacct|scontrol|sattach|sstat|sinfo|srun|shoal ..." >&2; exit 2; }
  prog=$1
  shift
fi

if [ "$prog" = install ]; then
  dir=${1:-$HOME/.local/bin}
  mkdir -p "$dir"
  cat "$0" > "$dir/.slurm.$$" && chmod +x "$dir/.slurm.$$" && mv -f "$dir/.slurm.$$" "$dir/slurm"
  for c in sbatch squeue scancel sacct scontrol sattach sstat sinfo srun shoal; do ln -sf slurm "$dir/$c"; done
  echo "Installed sbatch, squeue, scancel, sacct, scontrol, sattach, sstat, sinfo, srun and shoal in $dir."
  case ":$PATH:" in *":$dir:"*) ;; *) echo "Add it to your PATH: export PATH=\"$dir:\$PATH\"" ;; esac
  exit 0
fi

git rev-parse --show-toplevel >/dev/null 2>&1 || die "run this inside a clone of the project"
origin=$(git remote get-url origin 2>/dev/null) || die "this clone has no origin remote"
site=$(printf '%s' "$origin" | sed -E 's#^(https?://)([^@/]*@)?([^/]+).*#\1\3#')
project=$(printf '%s' "$origin" | sed -E 's#^https?://[^/]+/##; s#/+$##; s#\.git$##')
auth=${SS_AUTH:-$(git config --get-urlmatch http.extraheader "$site/" 2>/dev/null || true)}
# a job run elsewhere reports with its own token only (run-job), so that machine needs none of yours
[ -n "$auth" ] || [ "$prog" = run-job ] || die "no token for $site in this clone: give it to this clone, not globally, as $site/skill.md says: git config --add http.$site/.extraHeader '' && git config --add http.$site/.extraHeader 'Authorization: Bearer <token>'"
api="$site/api/repos/$project/jobs"
# What the site answers goes to stdout; when it refuses, its reason goes to stderr after "<command>: error: " with a
# failing exit, as Slurm's commands do. curl reads the token on its input (and run-job's from a file only this user can
# read): never on its command line, which every user of the machine can read (ps).
# A line the site adds about the project (X-Shoal-Note: where its best stands) goes to stderr, after the answer: a
# session reads it, and a pipe that counts or greps the answer does not.
call() {
  body=$(mktemp) head=$(mktemp)
  code=$(printf 'header = "%s"\n' "$auth" | curl -sS -K - -o "$body" -D "$head" -w '%{http_code}' -H 'Accept: text/plain' "$@") || { rm -f "$body" "$head"; die "could not reach $site"; }
  case "$code" in
    2*) cat "$body"; sed -n 's/^[Xx]-[Ss]hoal-[Nn]ote: *//p' "$head" | tr -d '\r' >&2; rm -f "$body" "$head" ;;
    *) msg=$(cat "$body"); rm -f "$body" "$head"; die "$msg" ;;
  esac
}

# Runs a command in a session of its own under the same process id, so that it outlives the shell that started it and
# a kill of its group (a cancel, the time limit) stops all it started: set -m does neither in a shell without a terminal
# (dash). Run it in the background, lead <command> &.
lead() {
  if command -v setsid >/dev/null 2>&1; then exec setsid "$@"; fi
  if command -v perl >/dev/null 2>&1; then exec perl -MPOSIX -e 'POSIX::setsid(); exec @ARGV' "$@"; fi
  exec nohup "$@"
}

# A duration as seconds: 90, 90s, 30m, 6h or 2d.
secs() { case "$1" in ''|*[!0-9smhd]*) return 1 ;; *d) echo $((${1%d} * 86400)) ;; *h) echo $((${1%h} * 3600)) ;; *m) echo $((${1%m} * 60)) ;; *s) echo "${1%s}" ;; *) echo "$1" ;; esac; }
# shoal wait <thing> [until <condition>] [--timeout 6h] [--notify [--for 24h]]: asks the site to hold the request until
# the condition holds, a minute at a time (the site holds one at most that long), and goes on with the condition the
# site answered, so a wait for the next change keeps the change it started from. The last answer goes to stdout, the
# document of the thing as path: value lines; it exits 0 once held, 1 when the time ran out first.
shoal_wait() {
  [ $# -ge 1 ] || die "usage: shoal wait <jobs/<id>|issues/<n>|routes/<branch>|checks/<key>|.> [until <condition>] [--timeout 6h] [--notify [--for 24h]]"
  won=$1
  shift
  wuntil='' wlimit=86400 wnotify='' whours=24
  while [ $# -gt 0 ]; do
    case "$1" in
      until) [ $# -ge 2 ] || die 'until needs a condition, as in: until "state == COMPLETED"'; wuntil=$2; shift 2 ;;
      --until=*) wuntil=${1#*=}; shift ;;
      --timeout|--for) [ $# -ge 2 ] || die "$1 needs a duration, such as 90s, 30m or 6h"; v=$(secs "$2") || die "$1: a duration such as 90s, 30m or 6h, not $2"; [ "$1" = --timeout ] && wlimit=$v || whours=$(((v + 3599) / 3600)); shift 2 ;;
      --timeout=*) wlimit=$(secs "${1#*=}") || die "--timeout: a duration such as 90s, 30m or 6h"; shift ;;
      --notify) wnotify=1; shift ;;
      *) die "unrecognized argument '$1': shoal wait <thing> [until <condition>] [--timeout 6h] [--notify [--for 24h]]" ;;
    esac
  done
  [ "$won" = . ] && won=''
  wapi="$site/api/repos/$project"
  if [ -n "$wnotify" ]; then
    call -X POST "$wapi/waiters" --data-urlencode "on=$won" --data-urlencode "until=$wuntil" --data-urlencode "hours=$whours"
    return 0
  fi
  wend=$(($(date +%s) + wlimit)) wtold=''
  while :; do
    wleft=$((wend - $(date +%s)))
    [ "$wleft" -gt 0 ] || wleft=0
    [ "$wleft" -le 60 ] || wleft=60
    wanswer=$(call -G "$wapi/wait" --data-urlencode "on=$won" --data-urlencode "until=$wuntil" --data-urlencode "wait=$wleft")
    wuntil=$(printf '%s\n' "$wanswer" | sed -n 's/^until: //p' | head -n 1)
    if printf '%s\n' "$wanswer" | head -n 1 | grep -q '^held: yes'; then printf '%s\n' "$wanswer"; return 0; fi
    # why what is waited for will not come for now, when the site says so (no runner judges the route): once, at once
    wnote=$(printf '%s\n' "$wanswer" | sed -n 's/^note: //p' | head -n 1)
    if [ -n "$wnote" ] && [ -z "$wtold" ]; then echo "$prog: $wnote" >&2; wtold=1; fi
    if [ "$(date +%s)" -ge "$wend" ]; then
      printf '%s\n' "$wanswer"
      echo "$prog: not held yet after $wlimit s; to wait on: shoal wait ${won:-.} until \"$wuntil\"" >&2
      return 1
    fi
  done
}
# The field of the answer to `shoal wait` named $1 (exit_code, state, …).
wfield() { printf '%s\n' "$2" | sed -n "s/^$1: //p" | head -n 1; }
# The exit code a job's end stands for, as sbatch --wait returns it: its own, or 1 when it ended without one.
wexit() { c=$(wfield exit_code "$1"); case "$c" in ''|*[!0-9]*) [ "$(wfield state "$1")" = COMPLETED ] && echo 0 || echo 1 ;; *) echo "$c" ;; esac; }

# run-job <id> <script> [arguments]: run a registered job here and report as its runner, with $SS_JOB_TOKEN; the
# site's answer to sbatch gave the rest ($SS_TIME_LIMIT, $SS_CHECKPOINT, $SS_OUTPUT, $SS_ROUTE_DIR). Everything it
# prints goes to its --output file (slurm-<id>.out) in this directory, as on a cluster, and to the site's log every half
# minute, which also tells the site it is alive. What it writes in this directory comes back when it ends (and every
# --checkpoint minutes); a cancel from the site (scancel), or the job's time limit, stops it: TERM, then KILL half a
# minute later. The arguments go to the script as $1 $2 ….
run_job() {
  id=$1 script=$2
  shift 2
  token=${SS_JOB_TOKEN:?run-job needs the job token in SS_JOB_TOKEN}
  rauth="Authorization: Job $token" rapi="$site/api/runner/jobs/$id"
  limit=${SS_TIME_LIMIT:-86400} every=${SS_CHECKPOINT:-} out=${SS_OUTPUT:-slurm-$id.out}
  mkdir -p "$(dirname "$out")"
  mark=$(mktemp) sent=$(mktemp) state=$(mktemp) rc=$(mktemp) hdr=$(mktemp)
  printf 'header = "%s"\n' "$rauth" > "$hdr"
  touch -r "$mark" "$sent"
  echo 0 > "$state"
  root=$(git rev-parse --show-toplevel)
  # the files written here since $1 (the job's start, or the last checkpoint), as paths relative to here (none of git's own)
  changed() { find . -type f -newer "$1" ! -path './.git/*' ! -name "$out.part" 2>/dev/null | sed 's#^\./##'; }
  enc() { printf '%s' "$1" | od -An -v -tx1 | tr -d ' \n' | sed 's/../%&/g; s#%2f#/#g'; } # a path as a URL may carry it
  put() { while IFS= read -r f; do [ "$(wc -c < "$f")" -le 5000000 ] && curl -sS -o /dev/null -X PUT -K "$hdr" --data-binary "@$f" "$rapi/outputs/$(enc "$f")" || true; done; }
  # a checkpoint sends what changed since the last one; the end sends all the job wrote, then the list of it, so what a
  # checkpoint brought and the job removed is dropped
  checkpoint() { touch "$sent.new"; changed "$sent" | put; mv "$sent.new" "$sent"; }
  bring() { changed "$mark" > "$sent.new"; put < "$sent.new"; [ -z "$every" ] || curl -sS -o /dev/null -X POST -K "$hdr" --data-binary "@$sent.new" "$rapi/outputs" || true; }
  report() { # the log since the last report; false once the site says the job no longer runs (cancelled, or lost)
    off=$(cat "$state") size=$(($(wc -c < "$out"))) # BSD wc pads the count with spaces, and it goes into a URL
    [ "$size" -gt "$off" ] || size=$off
    [ $((size - off)) -le 900000 ] || off=$((size - 900000)) # the site keeps a megabyte of log: a flood sends its latest part
    # (sh has no local variables: nothing here may be called code, the job's exit status)
    # ?at= says where the chunk starts: one sent again after a lost reply is not written twice, and a flood's skipped
    # part shows on the site as a line saying how much. With nothing new it is a heartbeat (BSD head refuses -c 0).
    if [ "$size" -gt "$off" ]; then
      http=$(tail -c +$((off + 1)) "$out" | head -c $((size - off)) | curl -sS -o /dev/null -w '%{http_code}' -X POST -K "$hdr" --data-binary @- "$rapi/log?at=$off" || echo 000)
    else
      http=$(curl -sS -o /dev/null -w '%{http_code}' -X POST -K "$hdr" --data-binary '' "$rapi/log?at=$off" || echo 000)
    fi
    [ "$http" = 409 ] && return 1
    [ "$http" = 200 ] && echo "$size" > "$state"
    return 0
  }
  : > "$out"
  # the job leads a process group of its own, so a cancel stops all it started; its exit status goes to a file
  lead env SLURM_JOB_ID="$id" SLURM_JOB_NAME="$(basename "$script")" SLURM_SUBMIT_DIR="$(pwd)" SS_INPUT="$root" SS_ROUTE_DIR="${SS_ROUTE_DIR:-}" \
    sh -c 'f=$1 rc=$2; shift 2; bash "$f" "$@"; echo $? > "$rc"' sh "$script" "$rc" "$@" >> "$out" 2>&1 &
  pid=$!
  # TERM to the job's group, then KILL if it is still there half a minute later, as Slurm does
  end_it() { kill -s TERM -- "-$pid" 2>/dev/null || kill -s TERM "$pid" 2>/dev/null || true; (sleep 30; kill -s KILL -- "-$pid" 2>/dev/null || kill -s KILL "$pid" 2>/dev/null) & killer=$!; }
  start=$(date +%s) last=$start timedout=false stopped=false killer=''
  while kill -0 "$pid" 2>/dev/null; do
    sleep 5
    now=$(date +%s)
    if [ $((now - start)) -ge "$limit" ]; then
      echo "slurmstepd: error: *** JOB $id ON $(hostname) CANCELLED AT $(date -u +%Y-%m-%dT%H:%M:%S) DUE TO TIME LIMIT ***" >> "$out"
      end_it
      timedout=true
      break
    fi
    [ $((now - last)) -ge 30 ] || continue
    last=$now
    report || { end_it; stopped=true; break; }
    [ -n "$every" ] && [ $(((now - start) / 60 % every)) -eq 0 ] && [ $((now - start)) -ge 60 ] && checkpoint
  done
  wait "$pid" 2>/dev/null || true
  [ -z "$killer" ] || kill "$killer" 2>/dev/null || true
  code=$(cat "$rc" 2>/dev/null || true)
  [ -n "$code" ] || code=137 # killed before it could say
  if $stopped; then rm -f "$mark" "$sent" "$sent.new" "$state" "$rc" "$hdr"; return 0; fi # the site ended it (scancel): nothing more to report
  report || true
  bring
  summary=$(grep -v '^[[:space:]]*$' "$out" | tail -n 1 | cut -c1-200 | sed 's/\\/\\\\/g; s/"/\\"/g' | tr -d '\000-\037')
  curl -sS -o /dev/null -X POST -K "$hdr" -H 'Content-Type: application/json' -d "{\"exit_code\": $code, \"timed_out\": $timedout, \"halted\": false, \"summary\": \"$summary\"}" "$rapi/finish" || true
  rm -f "$mark" "$sent" "$sent.new" "$state" "$rc" "$hdr"
}

case "$prog" in
run-job)
  [ $# -ge 2 ] || die "usage: SS_JOB_TOKEN=<token> slurm run-job <id> <script> [arguments]"
  run_job "$@"
  ;;
sbatch)
  args=$(mktemp) argv=$(mktemp)
  trap 'rm -f "$args" "$argv"' EXIT
  script='' here='' register='' await=''
  while [ $# -gt 0 ]; do
    case "$1" in
      --here) here=1; shift; continue ;;
      --register) here=1 register=1; shift; continue ;;
      -W|--wait) await=1; shift; continue ;;
      # the options that take a value, as the site's parser reads them (SHORT and TAKES in src/jobs.ts); it explains
      # why it refuses -e, -a and -d, so they are sent along too
      -J|-t|-c|-o|-e|-p|-G|-N|-n|-a|-d|--job-name|--time|--cpus-per-task|--mem|--gres|--gpus|--output|--error|--partition|--nodes|--ntasks|--array|--dependency|--checkpoint)
        [ $# -ge 2 ] || die "option $1 needs a value"
        printf '%s\n%s\n' "$1" "$2" >> "$args"
        shift 2 ;;
      -*) printf '%s\n' "$1" >> "$args"; shift ;;
      *) script=$1; shift; break ;;
    esac
  done
  [ -n "$script" ] || die "usage: sbatch [options] script.sbatch [arguments]"
  # a container that ends with the session that runs in it (a lab run's member says so with SHOAL_EPHEMERAL) would end a
  # job run here with it: tcsx-g1's members ran 161 of 338 jobs with --here, told they could leave, and 6 died so (one
  # run in the foreground, --here --wait, ends before the session does)
  [ -z "$here" ] || [ -n "$register" ] || [ -n "$await" ] || [ -z "${SHOAL_EPHEMERAL:-}" ] || die "--here: this container ends when your session does, and a job run here would end with it. Submit without --here and the site's runners run it, however long it takes."
  [ -f "$script" ] || die "unable to open file $script"
  # what follows the script is its arguments ($1 $2 …), kept with the job each as written: NUL ends each one
  [ $# -eq 0 ] || printf '%s\000' "$@" > "$argv"
  sha=$(git rev-parse HEAD)
  branch=$(git rev-parse --abbrev-ref HEAD)
  cwd=$(git rev-parse --show-prefix)
  file=$(git ls-files --full-name -- "$script" 2>/dev/null | head -n 1)
  if [ -z "$here" ]; then
    answer=$(call -X POST "$api" --data-urlencode "script@$script" --data-urlencode "args@$args" --data-urlencode "script_args@$argv" \
      --data-urlencode "sha=$sha" --data-urlencode "branch=$branch" --data-urlencode "cwd=$cwd" --data-urlencode "file=${file:-$script}")
    printf '%s\n' "$answer"
    [ -n "$await" ] || exit 0
    # --wait: back once the job has ended, with its exit code, as Slurm's sbatch --wait
    id=$(printf '%s\n' "$answer" | sed -n 's/^Submitted batch job \([0-9]*\).*/\1/p' | head -n 1)
    ended=$(shoal_wait "jobs/$id") || exit 1
    echo "Job $id ended: $(wfield state "$ended"), exit $(wexit "$ended")${ended:+. $(wfield summary "$ended")}"
    exit "$(wexit "$ended")"
  fi
  # a job run here runs the code you pushed: what git tracks must be as committed
  git diff --quiet HEAD -- || die "commit and push your changes first: a job run here runs the commit it is registered at"
  host=$(hostname 2>/dev/null || echo here)
  answer=$(call -X POST "$api" --data-urlencode "script@$script" --data-urlencode "args@$args" --data-urlencode "script_args@$argv" --data-urlencode "here=1" --data-urlencode "register=$register" --data-urlencode "host=$host" \
    --data-urlencode "sha=$sha" --data-urlencode "branch=$branch" --data-urlencode "cwd=$cwd" --data-urlencode "file=${file:-$script}")
  val() { printf '%s\n' "$answer" | sed -n "s/^$1=//p"; }
  id=$(val SS_JOB_ID)
  printf '%s\n' "$answer" | head -n 1
  if [ -n "$register" ]; then
    # the arguments as a shell reads them back: each in single quotes
    quoted=''
    for a in "$@"; do quoted="$quoted '$(printf '%s' "$a" | sed "s/'/'\\\\''/g")'"; done
    echo "Run it where the computation is, in a clone at $sha, from $cwd:"
    echo "  SS_JOB_TOKEN=$(val SS_JOB_TOKEN) SS_TIME_LIMIT=$(val SS_TIME_LIMIT) SS_CHECKPOINT=$(val SS_CHECKPOINT) SS_OUTPUT=$(val SS_OUTPUT) SS_ROUTE_DIR=$(val SS_ROUTE_DIR) slurm run-job $id $script$quoted"
    exit 0
  fi
  export SS_JOB_TOKEN="$(val SS_JOB_TOKEN)" SS_TIME_LIMIT="$(val SS_TIME_LIMIT)" SS_CHECKPOINT="$(val SS_CHECKPOINT)" SS_OUTPUT="$(val SS_OUTPUT)" SS_ROUTE_DIR="$(val SS_ROUTE_DIR)"
  # --wait: here, in the foreground, and back with its exit code
  if [ -n "$await" ]; then run_job "$id" "$script" "$@"; exit "${code:-1}"; fi
  # detached from this session: in a session of its own, so it outlives the shell (and the agent) that started it
  self=$(command -v slurm 2>/dev/null || echo "$0")
  # what goes wrong with the reporting itself (not the job's own output) goes to a file outside the directory
  wlog="${TMPDIR:-/tmp}/slurm-here-$id.log"
  lead sh "$self" run-job "$id" "$script" "$@" </dev/null >"$wlog" 2>&1 &
  echo "It runs here, detached: its output is $(val SS_OUTPUT) in this directory, and the site has its log, its checks and, once it ends, its result (git fetch origin refs/jobs/$id). You may leave. (Reporting problems, if any: $wlog)"
  ;;
squeue|sacct)
  q="format=$prog"
  if [ "$prog" = squeue ]; then takes='-u/--user, --me, -j/--jobs, -h/--noheader'; else takes='-j/--jobs, -u/--user, -a/--allusers'; fi
  while [ $# -gt 0 ]; do
    opt=$1 val=''
    case "$opt" in
      --user=*|--jobs=*) val=${opt#*=} opt=${opt%%=*} ;;
      -u|--user|-j|--jobs) [ $# -ge 2 ] || die "option $1 needs a value"; val=$2; shift ;;
    esac
    shift
    case "$prog:$opt" in
      *:-u|*:--user) q="$q&user=$val" ;;
      *:-j|*:--jobs) q="$q&id=$val" ;;
      squeue:--me) q="$q&user=me" ;;
      squeue:-h|squeue:--noheader) q="$q&noheader=1" ;;
      sacct:-a|sacct:--allusers) q="$q&user=*" ;;
      squeue:-a|squeue:--all|sacct:-X|sacct:--allocations|sacct:-b|sacct:--brief) ;;
      *) die "unrecognized option '$opt' (this $prog takes $takes)" ;;
    esac
  done
  call "$api?$q"
  ;;
scancel)
  [ $# -gt 0 ] || die "usage: scancel <jobid> ..."
  for id in "$@"; do call -X DELETE "$api/$id"; done
  ;;
scontrol)
  # scontrol show job <id>: the job as Slurm prints it; nothing else of scontrol's is offered
  [ "${1:-}" = show ] && { [ "${2:-}" = job ] || [ "${2:-}" = jobid ]; } && [ -n "${3:-}" ] || die "only scontrol show job <id> is offered here"
  call "$api/${3%%.*}?format=scontrol"
  ;;
sstat)
  [ "${1:-}" = -j ] && shift
  [ $# -eq 1 ] || die "usage: sstat -j <jobid>"
  call "$api/${1%%.*}?format=sstat"
  ;;
sinfo)
  call "$site/api/repos/$project/compute?format=sinfo"
  ;;
sattach)
  # the job's log, from its start, followed until the job ends
  [ $# -eq 1 ] || die "usage: sattach <jobid>"
  id=${1%%.*} from=0
  while :; do
    body=$(mktemp) head=$(mktemp)
    code=$(printf 'header = "%s"\n' "$auth" | curl -sS -K - -o "$body" -D "$head" -w '%{http_code}' -H 'Accept: text/plain' -G "$api/$id/log" --data-urlencode "from=$from" --data-urlencode "wait=30") || { rm -f "$body" "$head"; die "could not reach $site"; }
    case "$code" in 2*) ;; *) msg=$(cat "$body"); rm -f "$body" "$head"; die "$msg" ;; esac
    cat "$body"
    got=$(wc -c < "$body")
    next=$(sed -n 's/^[Xx]-[Ss]hoal-[Ll]og-[Nn]ext: *//p' "$head" | tr -d '\r')
    st=$(sed -n 's/^[Xx]-[Ss]hoal-[Jj]ob-[Ss]tate: *//p' "$head" | tr -d '\r')
    rm -f "$body" "$head"
    [ -z "$next" ] || from=$next
    case "$st" in PENDING|RUNNING) ;; *) [ "$got" -gt 0 ] || break ;; esac
  done
  ;;
srun)
  # srun --here <command>: the command run here as a job of the site's, in the foreground; its output goes to the
  # terminal once it ends, and to the site's log as it runs; what it writes in this directory comes back as any job's
  [ "${1:-}" = --here ] || die "srun runs on this machine only, as srun --here <command>: to run on the project's runners, write the command in a script and sbatch it"
  shift
  [ "${1:-}" = -- ] && shift
  [ $# -gt 0 ] || die "usage: srun --here <command> [arguments]"
  git diff --quiet HEAD -- || die "commit and push your changes first: a job run here runs the commit it is registered at"
  script=$(mktemp "${TMPDIR:-/tmp}/srun.XXXXXX")
  { echo '#!/bin/bash'; printf 'exec'; for a in "$@"; do printf " '%s'" "$(printf '%s' "$a" | sed "s/'/'\\\\''/g")"; done; echo; } > "$script"
  host=$(hostname 2>/dev/null || echo here)
  answer=$(call -X POST "$api" --data-urlencode "script@$script" --data-urlencode "here=1" --data-urlencode "host=$host" \
    --data-urlencode "sha=$(git rev-parse HEAD)" --data-urlencode "branch=$(git rev-parse --abbrev-ref HEAD)" --data-urlencode "cwd=$(git rev-parse --show-prefix)" --data-urlencode "file=srun")
  val() { printf '%s\n' "$answer" | sed -n "s/^$1=//p"; }
  id=$(val SS_JOB_ID)
  echo "srun: job $id runs here, on $host, as a job of the site's: $site/$project/jobs/$id" >&2
  export SS_JOB_TOKEN="$(val SS_JOB_TOKEN)" SS_TIME_LIMIT="$(val SS_TIME_LIMIT)" SS_CHECKPOINT='' SS_OUTPUT="${TMPDIR:-/tmp}/srun-$id.out" SS_ROUTE_DIR="$(val SS_ROUTE_DIR)"
  run_job "$id" "$script"
  cat "$SS_OUTPUT"
  rm -f "$SS_OUTPUT" "$script"
  exit "${code:-1}"
  ;;
shoal)
  [ "${1:-}" = wait ] || die "usage: shoal wait <thing> [until <condition>] [--timeout 6h] [--notify [--for 24h]]"
  shift
  shoal_wait "$@"
  ;;
*)
  die "unknown command (sbatch, squeue, scancel, sacct, scontrol, sattach, sstat, sinfo, srun, shoal or run-job)"
  ;;
esac
