#!/bin/sh
# In-pod workspace helper: `ws <subcommand> <fixed args> -- <data>`. Every subcommand's
# first stdout line is a header `WS <fields...>`; helper errors are `WS error <code> <msg>`
# with exit 2 (usage), 3 (no such call or file) or 4 (conflict). A command's own exit
# code goes in the header, never in the helper's exit status.

ROOT=${WS_ROOT:-/work}
CALLS=$ROOT/.ws/calls
CAP=30720
HEAD_BYTES=4096
TAIL_BYTES=26624
IN_LIMIT=1048576
TMPD=$ROOT/.ws/tmp
READ_CAP=131072  # bytes of lines one read returns
LINE_BYTES=8192  # bytes kept of each line read; the job cuts lines at 2000 characters
IMG_LIMIT=10485760
IMG_OUT=3750000  # bytes of image sent at most, so its base64 stays under 5 MB; larger PNGs go out as JPEG
RG_RAW=16777216
DNUM=${WS_DISPLAY:-0}  # the X display number; only a local run of the helper changes it
DPY=:$DNUM
APPS=$ROOT/.ws/apps
SHOTS=$ROOT/.ws/shots
APP_MAX=4
APP_WAIT=30       # seconds app-start waits for the app's window
APP_LOG_START=4096
APP_LOG_STOP=2048

die() { # code exit message...
  code=$1; st=$2; shift 2
  printf 'WS error %s %s\n' "$code" "$*"
  exit "$st"
}

# Milliseconds on the kernel's monotonic clock (10 ms steps). `date +%s%3N` is not used: some date
# implementations read the seconds and the nanoseconds separately, so successive calls can go back by
# up to a second.
now_ms() {
  read -r _up _ </proc/uptime
  _f=${_up#*.}
  case $_f in 0?) _f=${_f#0} ;; esac
  echo $((${_up%.*} * 1000 + _f * 10))
}

is_uint() { case $1 in '' | *[!0-9]*) return 1 ;; esac; }
is_pos() { is_uint "$1" && case $1 in 0*) return 1 ;; esac; }

# Prints the status header for call $1.
status_header() {
  _n=$1
  _log=$CALLS/$_n.log
  _total=0
  [ -f "$_log" ] && _total=$(wc -c <"$_log" | tr -d ' ')
  _start=$(cat "$CALLS/$_n.start" 2>/dev/null || now_ms)
  if [ -f "$CALLS/$_n.exit" ]; then
    _code=$(cat "$CALLS/$_n.exit")
    _end=$(cat "$CALLS/$_n.end" 2>/dev/null || now_ms)
    if [ -e "$CALLS/$_n.killed" ]; then _state=killed
    # 124 and 137 also come from the command itself (its own exit, an OOM kill), so
    # only a run that lasted its whole limit counts as timed out.
    elif { [ "$_code" = 124 ] || [ "$_code" = 137 ]; } &&
      [ $((_end - _start)) -ge $(($(cat "$CALLS/$_n.limit" 2>/dev/null || echo 0) * 1000)) ]; then _state=timed-out
    else _state=exited; fi
  else
    _code=-
    _end=$(now_ms)
    _state=running
  fi
  printf 'WS %s %s %s %s\n' "$_state" "$_code" "$((_end - _start))" "$_total"
}

# Prints the log of call $1 from byte offset $2, capped.
emit_log() {
  _log=$CALLS/$1.log
  [ -f "$_log" ] || return 0
  _total=$(wc -c <"$_log" | tr -d ' ')
  _since=$2
  [ "$_since" -gt "$_total" ] && _since=$_total
  _sel=$((_total - _since))
  if [ "$_sel" -gt "$CAP" ]; then
    tail -c +$((_since + 1)) "$_log" | head -c "$HEAD_BYTES"
    printf '\n[ws: %s bytes cut; full log %s]\n' "$((_sel - HEAD_BYTES - TAIL_BYTES))" "$_log"
    tail -c "$TAIL_BYTES" "$_log"
  else
    tail -c +$((_since + 1)) "$_log"
  fi
}

# Waits up to $2 seconds for call $1 to end.
wait_exit() {
  _deadline=$(($(now_ms) + $2 * 1000))
  while [ ! -f "$CALLS/$1.exit" ] && [ "$(now_ms)" -lt "$_deadline" ]; do sleep 0.05; done
}

# A new temporary file under .ws/tmp, its path on stdout.
new_tmp() {
  mkdir -p "$TMPD" 2>/dev/null
  mktemp "$TMPD/t.XXXXXX" 2>/dev/null
}

file_size() { wc -c <"$1" | tr -d ' '; }

# png, jpeg, gif or webp from the file's first bytes; empty for anything else.
image_kind() {
  _sig=$(od -An -tx1 -N12 "$1" 2>/dev/null | tr -d ' \n')
  case $_sig in
    89504e470d0a1a0a*) echo png ;;
    ffd8ff*) echo jpeg ;;
    474946383761* | 474946383961*) echo gif ;;
    52494646????????57454250) echo webp ;;
  esac
}

im_identify() {
  if command -v magick >/dev/null 2>&1; then magick identify "$@"
  elif command -v identify >/dev/null 2>&1; then identify "$@"
  else return 127; fi
}

im_convert() {
  if command -v magick >/dev/null 2>&1; then magick "$@"
  elif command -v convert >/dev/null 2>&1; then convert "$@"
  else return 127; fi
}

# Width and height of the first frame of image $1, as "w h"; fails when unreadable.
image_dims() {
  _d=$(im_identify -format '%w %h' "${1}[0]" 2>/dev/null) || return 1
  case $_d in
    [1-9]*' '[1-9]*) echo "$_d" ;;
    *) return 1 ;;
  esac
}

# ---- display ----------------------------------------------------------------

# Starts Xvfb detached from this call, its pid in .ws/xvfb.pid.
start_xvfb() {
  setsid Xvfb "$DPY" -screen 0 2880x1800x24 -dpi 96 -nolisten tcp -noreset </dev/null >>"$ROOT/.ws/xvfb.log" 2>&1 9>&- &
  echo "$!" >"$ROOT/.ws/xvfb.pid"
}

# A pid this helper may wait on or signal: a positive integer above 1 (never init, never a process group of all).
valid_pid() { is_pos "$1" && [ "$1" -gt 1 ]; }

# The Xvfb pid from .ws/xvfb.pid when that process is still Xvfb; empty otherwise.
xvfb_pid() {
  _xp=$(cat "$ROOT/.ws/xvfb.pid" 2>/dev/null)
  valid_pid "$_xp" && [ "$(cat "/proc/$_xp/comm" 2>/dev/null)" = Xvfb ] && echo "$_xp"
}

x_up() { xwininfo -display "$DPY" -root >/dev/null 2>&1; }

# Waits up to $1 seconds for the display to answer.
wait_display() {
  _deadline=$(($(now_ms) + $1 * 1000))
  until x_up; do
    [ "$(now_ms)" -lt "$_deadline" ] || return 1
    sleep 0.1
  done
}

need_x() {
  command -v Xvfb >/dev/null 2>&1 || die nodisplay 2 "Xvfb is not installed in this image"
  { command -v xwininfo && command -v xprop; } >/dev/null 2>&1 || die nodisplay 2 "xwininfo and xprop (x11-utils) are not installed in this image"
}

# Makes sure the display answers, starting Xvfb again if it died; writes 1 to file $1 when it did, else 0.
# Errors go to stdout as the call's header.
ensure_display() {
  need_x
  echo 0 >"$1"
  x_up && return 0
  _xp=$(xvfb_pid)
  if [ -n "$_xp" ]; then
    # Still starting, or hung.
    wait_display 5 && return 0
    kill -KILL "$_xp" 2>/dev/null
    sleep 0.2
  fi
  rm -f "/tmp/.X$DNUM-lock" "/tmp/.X11-unix/X$DNUM"
  echo "ws: display $DPY was not running; starting Xvfb again ($(date -u +%FT%TZ))" >>"$ROOT/.ws/xvfb.log"
  start_xvfb
  wait_display 10 || die nodisplay 2 "Xvfb did not start; see $ROOT/.ws/xvfb.log"
  echo 1 >"$1"
}

# Top-level windows, one id per line. Without a window manager, app windows are the root's children.
top_windows() {
  xwininfo -display "$DPY" -root -children 2>/dev/null | sed -n 's/^ *\(0x[0-9a-f]*\) .*/\1/p'
}

# "x y w h" of window $1 (an id, or -root) when it is viewable; fails otherwise.
win_geom() {
  if [ "$1" = -root ]; then _i=$(xwininfo -display "$DPY" -root 2>/dev/null) || return 1
  else _i=$(xwininfo -display "$DPY" -id "$1" 2>/dev/null) || return 1; fi
  printf '%s\n' "$_i" | grep -qx ' *Map State: IsViewable' || return 1
  printf '%s\n' "$_i" | sed -n 's/^ *Absolute upper-left X: *\(-\{0,1\}[0-9]*\)$/x \1/p; s/^ *Absolute upper-left Y: *\(-\{0,1\}[0-9]*\)$/y \1/p; s/^ *Width: *\([0-9]*\)$/w \1/p; s/^ *Height: *\([0-9]*\)$/h \1/p' |
    { x=; y=; w=; h=
      while read -r _k _v; do eval "$_k=\$_v"; done
      [ -n "$x" ] && [ -n "$y" ] && [ -n "$w" ] && [ -n "$h" ] && echo "$x $y $w $h"; }
}

# The session (an app's pid, since it runs as a session leader) of the process that owns window $1; empty when unknown.
win_session() {
  _wp=$(xprop -display "$DPY" -id "$1" _NET_WM_PID 2>/dev/null | sed -n 's/^_NET_WM_PID(CARDINAL) = \([0-9]*\)$/\1/p')
  [ -n "$_wp" ] || return 0
  sed 's/.*) //' "/proc/$_wp/stat" 2>/dev/null | cut -d' ' -f4
}

# find_window <n> <pid> [<before>]: "id x y w h" of the largest viewable window of app <n> (pid <pid>); with <before>
# (the window list from before the launch), else the largest new window no process claims. A window another running
# app's .win names is never this app's (a display started again reuses ids, so only running apps count).
find_window() {
  _others=$(for _o in $(live_apps); do [ "$_o" != "$1" ] && cat "$APPS/$_o.win"; done 2>/dev/null)
  _best=; _area=0; _new=; _narea=0
  for _w in $(top_windows); do
    [ -n "$_others" ] && printf '%s\n' "$_others" | grep -qx "$_w" && continue
    _s=$(win_session "$_w")
    if [ -n "$_s" ]; then [ "$_s" = "$2" ] || continue
    elif [ -z "${3:-}" ] || grep -qx "$_w" "$3" 2>/dev/null; then continue; fi
    _g=$(win_geom "$_w") || continue
    _ww=$(echo "$_g" | cut -d' ' -f3); _hh=$(echo "$_g" | cut -d' ' -f4)
    [ "$_ww" -gt 1 ] && [ "$_hh" -gt 1 ] || continue
    _a=$((_ww * _hh))
    if [ -n "$_s" ]; then
      [ "$_a" -gt "$_area" ] && { _area=$_a; _best="$_w $_g"; }
    else
      [ "$_a" -gt "$_narea" ] && { _narea=$_a; _new="$_w $_g"; }
    fi
  done
  [ -n "$_best" ] || _best=$_new
  [ -n "$_best" ] && echo "$_best"
}

im_import() {
  if command -v magick >/dev/null 2>&1; then magick import "$@"
  elif command -v import >/dev/null 2>&1; then import "$@"
  else return 127; fi
}

cmd_init() {
  boot=$(now_ms)
  mkdir -p "$ROOT/.ws/calls" "$ROOT/.ws/locks" "$ROOT/src" "$ROOT/home" || die io 2 "cannot create $ROOT"
  # A call an earlier pod on this volume left without an exit ended with that pod: mark it killed,
  # so its status says so and a kill never signals a pid of this pod.
  for s in "$CALLS"/*.start; do
    [ -f "$s" ] || continue
    n=${s##*/}; n=${n%.start}
    is_pos "$n" && [ ! -f "$CALLS/$n.exit" ] || continue
    st=$(cat "$s" 2>/dev/null)
    is_uint "$st" && [ "$st" -lt "$boot" ] || continue
    : >"$CALLS/$n.killed"
    echo "$boot" >"$CALLS/$n.end"
    echo 137 >"$CALLS/$n.exit.tmp" && mv "$CALLS/$n.exit.tmp" "$CALLS/$n.exit"
  done
  # A git of an earlier pod that died mid-command leaves its lock; no git of this pod runs yet.
  rm -f "$ROOT/src/.git/index.lock"
  printf 'WS ok init\n'
  if command -v Xvfb >/dev/null 2>&1; then
    start_xvfb
  else
    echo "ws: Xvfb not installed, skipping display"
  fi
  # app-start may have started Xvfb again, so the pid file names the one to stop.
  trap '_xp=$(xvfb_pid); [ -n "$_xp" ] && kill "$_xp" 2>/dev/null; exit 0' TERM INT
  while :; do
    sleep 1 &
    wait $!
  done
}

cmd_run() {
  [ $# -ge 2 ] || die usage 2 "run <n> <timeout_sec> [--cwd <dir>] [--background] -- <argv...>"
  n=$1; t=$2; shift 2
  is_pos "$n" || die usage 2 "call number must be a positive integer"
  is_pos "$t" || die usage 2 "timeout must be a positive integer"
  cwd=$ROOT/src
  bg=0
  while [ $# -gt 0 ]; do
    case $1 in
      --cwd) [ $# -ge 2 ] || die usage 2 "--cwd needs a value"; cwd=$2; shift 2 ;;
      --background) bg=1; shift ;;
      --) shift; break ;;
      *) die usage 2 "unknown argument $1" ;;
    esac
  done
  [ $# -gt 0 ] || die usage 2 "missing command after --"
  mkdir -p "$CALLS" || die io 2 "cannot create $CALLS"
  prune_calls
  for f in "$CALLS/$n".*; do
    [ -e "$f" ] && die conflict 4 "call $n already used"
  done
  start=$(now_ms)
  (set -C; echo "$start" >"$CALLS/$n.start") 2>/dev/null || die conflict 4 "call $n already used"
  echo "$t" >"$CALLS/$n.limit"
  head -c $((IN_LIMIT + 1)) >"$CALLS/$n.in"
  if [ "$(wc -c <"$CALLS/$n.in" | tr -d ' ')" -gt "$IN_LIMIT" ]; then
    rm -f "$CALLS/$n.in" "$CALLS/$n.start"
    die usage 2 "stdin larger than $IN_LIMIT bytes"
  fi
  : >"$CALLS/$n.log"
  # shellcheck disable=SC2016
  setsid sh -c '
    c=$1; n=$2; t=$3; d=$4; HOME=$5; shift 5
    export HOME; DISPLAY=:0; export DISPLAY
    if cd "$d" 2>/dev/null; then
      timeout -k 5 "$t" "$@" <"$c/$n.in" >"$c/$n.log" 2>&1 &
      tp=$!
      echo "$tp" >"$c/$n.pid"
      wait "$tp"; rc=$?
    else
      echo "ws: no such directory: $d" >"$c/$n.log"; rc=127
    fi
    read -r _up _ </proc/uptime
    _f=${_up#*.}
    case $_f in 0?) _f=${_f#0} ;; esac
    echo $((${_up%.*} * 1000 + _f * 10)) >"$c/$n.end"
    echo "$rc" >"$c/$n.exit.tmp"
    mv "$c/$n.exit.tmp" "$c/$n.exit"
  ' ws-wrap "$CALLS" "$n" "$t" "$cwd" "$ROOT/home" "$@" </dev/null >/dev/null 2>&1 &
  if [ "$bg" = 1 ]; then
    printf 'WS started %s\n' "$n"
    return 0
  fi
  while [ ! -f "$CALLS/$n.exit" ]; do sleep 0.05; done
  status_header "$n"
  emit_log "$n" 0
}

# Deletes the files of calls that ended more than a day ago. A call without an exit file is never touched.
prune_calls() {
  find "$CALLS" -maxdepth 1 -name '*.exit' -mmin +1440 2>/dev/null | while read -r _x; do
    _b=${_x%.exit}
    case ${_b##*/} in '' | *[!0-9]*) continue ;; esac
    rm -f "$_b".start "$_b".limit "$_b".in "$_b".log "$_b".pid "$_b".end "$_b".exit "$_b".exit.tmp
  done
}

need_call() {
  is_pos "$1" || die usage 2 "call number must be a positive integer"
  [ -f "$CALLS/$1.start" ] || die nocall 3 "no such call $1"
}

cmd_status() {
  [ $# -ge 1 ] || die usage 2 "status <n> [--wait <sec>] [--since <bytes>]"
  n=$1; shift
  need_call "$n"
  wait=0; since=0
  while [ $# -gt 0 ]; do
    case $1 in
      --wait) [ $# -ge 2 ] || die usage 2 "--wait needs a value"; wait=$2; shift 2 ;;
      --since) [ $# -ge 2 ] || die usage 2 "--since needs a value"; since=$2; shift 2 ;;
      *) die usage 2 "unknown argument $1" ;;
    esac
  done
  is_uint "$wait" && [ "$wait" -le 300 ] || die usage 2 "--wait must be 0-300"
  is_uint "$since" || die usage 2 "--since must be a byte offset"
  wait_exit "$n" "$wait"
  status_header "$n"
  emit_log "$n" "$since"
}

cmd_kill() {
  [ $# -eq 1 ] || die usage 2 "kill <n>"
  n=$1
  need_call "$n"
  if [ ! -f "$CALLS/$n.exit" ]; then
    : >"$CALLS/$n.killed"
    wait_pid=0
    while [ ! -f "$CALLS/$n.pid" ] && [ ! -f "$CALLS/$n.exit" ] && [ "$wait_pid" -lt 40 ]; do
      sleep 0.05; wait_pid=$((wait_pid + 1))
    done
    pid=$(cat "$CALLS/$n.pid" 2>/dev/null)
    if [ -n "$pid" ] && [ ! -f "$CALLS/$n.exit" ]; then
      kill -TERM -- "-$pid" 2>/dev/null || kill -TERM "$pid" 2>/dev/null
      wait_exit "$n" 5
      if [ ! -f "$CALLS/$n.exit" ]; then
        kill -KILL -- "-$pid" 2>/dev/null || kill -KILL "$pid" 2>/dev/null
        wait_exit "$n" 5
      fi
    fi
  fi
  status_header "$n"
}

cmd_put() {
  [ $# -ge 1 ] || die usage 2 "put <path> [--expect <sha256>|none]"
  p=$1; shift
  expect=
  while [ $# -gt 0 ]; do
    case $1 in
      --expect) [ $# -ge 2 ] || die usage 2 "--expect needs a value"; expect=$2; shift 2 ;;
      *) die usage 2 "unknown argument $1" ;;
    esac
  done
  case $p in
    /*) ;;
    *) die usage 2 "path must be absolute" ;;
  esac
  case $p in
    */.. | */../* | */. | */./* | *//*) die usage 2 "path must not contain . or .. components" ;;
  esac
  case $p in
    "$ROOT"/*) ;;
    *) die usage 2 "path must be under $ROOT" ;;
  esac
  # Writes go to the file a link points at, which must also be under ROOT, so a link
  # is never replaced by a regular file.
  dir=$(dirname "$p")
  mkdir -p "$dir" || die io 2 "cannot create $dir"
  root=$(readlink -f -- "$ROOT") || die io 2 "cannot resolve $ROOT"
  real=$(readlink -f -- "$p") || die io 2 "cannot resolve $p"
  case $real in
    "$root"/*) ;;
    *) die usage 2 "$p resolves to $real, outside $ROOT" ;;
  esac
  [ -d "$real" ] && die isdir 2 "$p is a directory"
  rdir=$(dirname "$real")
  mkdir -p "$ROOT/.ws/locks" || die io 2 "cannot create lock dir"
  tmp=$(mktemp "$rdir/.ws-put.XXXXXX") || die io 2 "cannot write in $rdir"
  # stdin is read before the lock, so the check and the replace happen together.
  cat >"$tmp" || { rm -f "$tmp"; die io 2 "cannot read the new content"; }
  key=$(printf '%s' "$real" | sha256sum | cut -d' ' -f1)
  (
    flock 9
    if [ -e "$real" ]; then
      cur=$(sha256sum <"$real" | cut -d' ' -f1)
      mode=$(stat -c %a "$real") || die io 2 "cannot read the mode of $p"
    else
      cur=none
      mode=644
    fi
    if [ -n "$expect" ] && [ "$expect" != "$cur" ]; then
      die conflict 4 "$cur"
    fi
    chmod "$mode" "$tmp" || die io 2 "cannot set the mode of $p"
    bytes=$(wc -c <"$tmp" | tr -d ' ')
    sha=$(sha256sum <"$tmp" | cut -d' ' -f1)
    mv -f "$tmp" "$real" || die io 2 "cannot replace $p"
    printf 'WS ok %s %s\n' "$bytes" "$sha"
  ) 9>"$ROOT/.ws/locks/$key"
  st=$?
  rm -f "$tmp"
  return "$st"
}

need_file() {
  case $1 in
    /*) ;;
    *) die usage 2 "path must be absolute" ;;
  esac
  [ -e "$1" ] || die nofile 3 "no such file $1"
  [ -d "$1" ] && die isdir 2 "$1 is a directory"
  [ -f "$1" ] || die nofile 3 "$1 is not a regular file"
}

# image <path> <max_edge>: `WS ok image <bytes> <w> <h> <out_w> <out_h>`, then the image, its long
# edge scaled down to max_edge. Larger PNG output goes out as JPEG.
cmd_image() {
  [ $# -eq 2 ] || die usage 2 "image <path> <max_edge>"
  p=$1; m=$2
  is_pos "$m" || die usage 2 "max_edge must be a positive integer"
  need_file "$p"
  [ -n "$(image_kind "$p")" ] || die notimage 2 "not a PNG, JPEG, GIF or WebP image"
  size=$(file_size "$p")
  [ "$size" -le "$IMG_LIMIT" ] || die toolarge 2 "$size bytes; images are read up to $IMG_LIMIT bytes"
  image_out image "$p" "$m"
}

# image_out <header fields> <path> <max_edge>: `WS ok <fields> <bytes> <w> <h> <out_w> <out_h>`, then the image.
image_out() {
  _pre=$1; p=$2; m=$3
  kind=$(image_kind "$p")
  size=$(file_size "$p")
  dims=$(image_dims "$p") || die image 2 "cannot read the image size (is ImageMagick installed?)"
  w=${dims% *}; h=${dims#* }
  long=$w
  [ "$h" -gt "$long" ] && long=$h
  if [ "$long" -le "$m" ] && [ "$size" -le "$IMG_OUT" ]; then
    printf 'WS ok %s %s %s %s %s %s\n' "$_pre" "$size" "$w" "$h" "$w" "$h"
    cat "$p"
    return 0
  fi
  tmp=$(new_tmp) || die io 2 "cannot write in $TMPD"
  out=png
  [ "$kind" = jpeg ] && out=jpeg
  if ! im_convert "${p}[0]" -auto-orient -resize "${m}x${m}>" -strip -quality 85 "$out:$tmp" 2>/dev/null; then
    rm -f "$tmp"; die image 2 "cannot scale the image"
  fi
  if [ "$out" = png ] && [ "$(file_size "$tmp")" -gt "$IMG_OUT" ]; then
    im_convert "png:$tmp" -quality 85 "jpeg:$tmp" 2>/dev/null || { rm -f "$tmp"; die image 2 "cannot scale the image"; }
  fi
  if [ "$(file_size "$tmp")" -gt "$IMG_OUT" ]; then
    rm -f "$tmp"; die toolarge 2 "the scaled image is larger than $IMG_OUT bytes"
  fi
  nd=$(image_dims "$tmp") || { rm -f "$tmp"; die image 2 "cannot read the scaled image"; }
  printf 'WS ok %s %s %s %s %s %s\n' "$_pre" "$(file_size "$tmp")" "$w" "$h" "${nd% *}" "${nd#* }"
  cat "$tmp"
  rm -f "$tmp"
}

# read <path> <offset> <limit> <max_edge>: an image as `image` prints it; a text file as
# `WS ok text <lines> <bytes>` and lines offset.. (at most limit of them, each cut at
# LINE_BYTES, READ_CAP in all). A binary file is `WS error binary <bytes> <type>`.
cmd_read() {
  [ $# -eq 4 ] || die usage 2 "read <path> <offset> <limit> <max_edge>"
  p=$1; o=$2; l=$3; m=$4
  is_pos "$o" || die usage 2 "offset must be a positive integer"
  is_pos "$l" || die usage 2 "limit must be a positive integer"
  need_file "$p"
  if [ -n "$(image_kind "$p")" ]; then
    cmd_image "$p" "$m"
    return
  fi
  size=$(file_size "$p")
  if [ "$(head -c 8192 "$p" | wc -c)" -ne "$(head -c 8192 "$p" | tr -d '\000' | wc -c)" ]; then
    type=$(file -b --mime-type "$p" 2>/dev/null) || type=
    die binary 2 "$size ${type:-unknown}"
  fi
  lines=$(wc -l <"$p" | tr -d ' ')
  [ "$size" -gt 0 ] && [ "$(tail -c 1 "$p" | od -An -tx1 | tr -d ' \n')" != 0a ] && lines=$((lines + 1))
  printf 'WS ok text %s %s\n' "$lines" "$size"
  end=$((o + l - 1))
  sed -n "${o},${end}p;${end}q" "$p" | cut -b "1-$LINE_BYTES" | head -c "$READ_CAP"
}

# cat <path> <max_bytes>: `WS ok <bytes> <sha256>`, then the file as it was hashed.
cmd_cat() {
  [ $# -eq 2 ] || die usage 2 "cat <path> <max_bytes>"
  p=$1; max=$2
  is_uint "$max" || die usage 2 "max_bytes must be a byte count"
  need_file "$p"
  size=$(file_size "$p")
  [ "$size" -le "$max" ] || die toolarge 2 "$size bytes"
  tmp=$(new_tmp) || die io 2 "cannot write in $TMPD"
  cat "$p" >"$tmp" || { rm -f "$tmp"; die io 2 "cannot read $p"; }
  printf 'WS ok %s %s\n' "$(file_size "$tmp")" "$(sha256sum <"$tmp" | cut -d' ' -f1)"
  cat "$tmp"
  rm -f "$tmp"
}

# rg <path> <timeout_sec> <limit> -- <rg options...>: ripgrep over path, from path's directory
# (so globs match relative to it), with stderr merged. `WS ok <rg exit> <output lines>`, then
# the first limit lines, CAP bytes at most.
cmd_rg() {
  [ $# -ge 4 ] && [ "$4" = -- ] || die usage 2 "rg <path> <timeout_sec> <limit> -- <rg options...>"
  p=$1; t=$2; l=$3; shift 4
  is_pos "$t" || die usage 2 "timeout must be a positive integer"
  is_pos "$l" || die usage 2 "limit must be a positive integer"
  case $p in
    /*) ;;
    *) die usage 2 "path must be absolute" ;;
  esac
  [ -e "$p" ] || die nofile 3 "no such file or directory $p"
  if [ -d "$p" ]; then d=$p; else d=$(dirname "$p"); fi
  cd "$d" || die io 2 "cannot enter $d"
  tmp=$(new_tmp) || die io 2 "cannot write in $TMPD"
  { timeout -k 5 "$t" rg --no-config --color never "$@" "$p" 2>&1; echo "$?" >"$tmp.rc"; } | head -c "$RG_RAW" >"$tmp"
  rc=$(cat "$tmp.rc" 2>/dev/null || echo 2)
  printf 'WS ok %s %s\n' "$rc" "$(wc -l <"$tmp" | tr -d ' ')"
  head -n "$l" "$tmp" | head -c "$CAP"
  rm -f "$tmp" "$tmp.rc"
}

cmd_untar() {
  [ $# -eq 0 ] || die usage 2 "untar takes no arguments"
  mkdir -p "$ROOT/src" "$ROOT/home" || die io 2 "cannot create $ROOT/src"
  if [ -n "$(ls -A "$ROOT/src" 2>/dev/null)" ]; then
    die conflict 4 "$ROOT/src is not empty"
  fi
  tar -x -f - -C "$ROOT/src" --no-same-owner --no-same-permissions >&2 || die tar 2 "tar extraction failed"
  cd "$ROOT/src" || die io 2 "cannot enter $ROOT/src"
  HOME=$ROOT/home
  export HOME
  GIT_AUTHOR_NAME=workspace GIT_AUTHOR_EMAIL=workspace@localhost
  GIT_COMMITTER_NAME=workspace GIT_COMMITTER_EMAIL=workspace@localhost
  # Fixed dates make the same tree give the same base commit hash after a rebuild.
  GIT_AUTHOR_DATE="2000-01-01T00:00:00+0000" GIT_COMMITTER_DATE="2000-01-01T00:00:00+0000"
  export GIT_AUTHOR_NAME GIT_AUTHOR_EMAIL GIT_COMMITTER_NAME GIT_COMMITTER_EMAIL GIT_AUTHOR_DATE GIT_COMMITTER_DATE
  git init -q >&2 || die git 2 "git init failed"
  git add -A >&2 || die git 2 "git add failed"
  git -c core.hooksPath=/dev/null -c commit.gpgsign=false -c user.name=workspace -c user.email=workspace@localhost \
    commit -q --allow-empty -m base >&2 || die git 2 "git commit failed"
  printf 'WS ok %s\n' "$(git rev-parse HEAD)"
}

# ---- apps -------------------------------------------------------------------

# Waits up to $2 seconds for file $1 to exist.
wait_file() {
  _deadline=$(($(now_ms) + $2 * 1000))
  while [ ! -f "$1" ] && [ "$(now_ms)" -lt "$_deadline" ]; do sleep 0.05; done
}

# The apps still running, one call number per line. One whose wrapper ended without writing its exit is not, nor one
# that has no pid a few seconds after its start (its wrapper never launched it).
live_apps() {
  for _f in "$APPS"/*.start; do
    [ -e "$_f" ] || continue
    _m=${_f##*/}; _m=${_m%.start}
    [ -f "$APPS/$_m.exit" ] && continue
    _p=$(cat "$APPS/$_m.pid" 2>/dev/null)
    if [ -z "$_p" ]; then
      _st=$(cat "$_f" 2>/dev/null)
      is_uint "$_st" && [ $(($(now_ms) - _st)) -lt 5000 ] && echo "$_m"
      continue
    fi
    valid_pid "$_p" && kill -0 "$_p" 2>/dev/null && echo "$_m"
  done
}

env_name_ok() {
  case $1 in
    '' | [!A-Z]* | *[!A-Z0-9_]*) return 1 ;;
    DISPLAY | HOME | WINIT_X11_SCALE_FACTOR | VK_* | LP_* | XDG_*) return 1 ;;
  esac
  [ ${#1} -le 64 ]
}

# check_app_args <k> <NAME=VALUE>... -- <args...>
check_app_args() {
  _k=$1; shift
  is_uint "$_k" && [ "$_k" -le 16 ] || die usage 2 "at most 16 env vars"
  _i=0
  while [ "$_i" -lt "$_k" ]; do
    [ $# -ge 1 ] && [ "$1" != -- ] || die usage 2 "fewer env vars than $_k"
    case $1 in *=*) ;; *) die usage 2 "env var $1 has no =" ;; esac
    env_name_ok "${1%%=*}" || die usage 2 "env var ${1%%=*} is not allowed"
    shift; _i=$((_i + 1))
  done
  [ "${1:-}" = -- ] || die usage 2 "missing -- after the env vars"
  shift
  [ $# -le 32 ] || die usage 2 "at most 32 args"
}

need_app() {
  is_pos "$1" || die usage 2 "app must be a positive integer"
  [ -f "$APPS/$1.start" ] || die noapp 3 "no such app $1"
}

# app-start <n> <scale> <binary> <k> <NAME=VALUE>... -- <args...>: starts the app on the display and waits up to
# APP_WAIT seconds for its window. `WS ok app <pid> <window> <x> <y> <w> <h> <restarted>`; `WS ok exited <code>` or
# `WS ok nowindow <pid> <restarted>` followed by the log's tail. A call number already started is not started again:
# the call waits for and reports that app, so a resumed job does not start it twice.
cmd_app_start() {
  [ $# -ge 5 ] || die usage 2 "app-start <n> <scale> <binary> <k> <NAME=VALUE>... -- <args...>"
  n=$1
  is_pos "$n" || die usage 2 "call number must be a positive integer"
  [ -f "$APPS/$n.start" ] || launch_app "$@"
  app_wait "$n"
}

launch_app() {
  n=$1; scale=$2; bin=$3; k=$4; shift 3
  case $scale in 1 | 2) ;; *) die usage 2 "scale must be 1 or 2" ;; esac
  check_app_args "$@"
  shift
  case $bin in
    "$ROOT"/*) ;;
    *) die usage 2 "binary must be under $ROOT" ;;
  esac
  root=$(readlink -f -- "$ROOT") || die io 2 "cannot resolve $ROOT"
  real=$(readlink -f -- "$bin") || die nofile 3 "no such file $bin"
  case $real in
    "$root"/*) ;;
    *) die usage 2 "$bin resolves to $real, outside $ROOT" ;;
  esac
  [ -f "$real" ] || die nofile 3 "no such file $bin"
  [ -x "$real" ] || die notexec 2 "$bin is not executable"
  { setsid_bin=$(command -v setsid) && env_bin=$(command -v env); } || die io 2 "setsid or env is not installed"
  mkdir -p "$APPS" "$ROOT/.ws/locks" || die io 2 "cannot create $APPS"
  (
    flock 9
    [ ! -f "$APPS/$n.start" ] || exit 0
    [ "$(live_apps | wc -l)" -lt "$APP_MAX" ] || die limit 2 "$APP_MAX apps are running; end one with app_stop"
    ensure_display "$APPS/$n.restarted"
    top_windows >"$APPS/$n.before"
    now_ms >"$APPS/$n.start"
    : >"$APPS/$n.log"
    # The wrapper sets only fixed variables; the session's env reaches the app through env(1), so no value can change
    # the wrapper's own shell, and it always records the pid and the exit code. setsid execs the app in place, in a
    # session of its own, so app-stop signals the app and its children but not the wrapper.
    # shellcheck disable=SC2016
    setsid sh -c '
      a=$1; n=$2; s=$3; HOME=$4; dir=$5; DISPLAY=$6; sid=$7; envb=$8; bin=$9; shift 9
      k=$1; shift
      WGPU_BACKEND=vulkan; LP_NUM_THREADS=4; WINIT_X11_SCALE_FACTOR=$s
      export HOME DISPLAY WGPU_BACKEND LP_NUM_THREADS WINIT_X11_SCALE_FACTOR
      if [ -z "${VK_ICD_FILENAMES:-}" ]; then
        for f in /usr/share/vulkan/icd.d/lvp_icd*.json; do [ -e "$f" ] && { VK_ICD_FILENAMES=$f; export VK_ICD_FILENAMES; }; break; done
      fi
      # "NAME=VALUE... -- args..." becomes "NAME=VALUE... <setsid> <bin> args...".
      total=$#; i=0
      while [ "$i" -lt "$total" ]; do
        if [ "$i" -eq "$k" ]; then set -- "$@" "$sid" "$bin"; else set -- "$@" "$1"; fi
        shift; i=$((i + 1))
      done
      cd "$dir" || cd /
      "$envb" "$@" </dev/null >"$a/$n.log" 2>&1 &
      ap=$!
      echo "$ap" >"$a/$n.pid"
      wait "$ap"; rc=$?
      read -r _up _ </proc/uptime
      _f=${_up#*.}
      case $_f in 0?) _f=${_f#0} ;; esac
      echo $((${_up%.*} * 1000 + _f * 10)) >"$a/$n.end"
      echo "$rc" >"$a/$n.exit.tmp"
      mv "$a/$n.exit.tmp" "$a/$n.exit"
    ' ws-app "$APPS" "$n" "$scale" "$ROOT/home" "$ROOT/src" "$DPY" "$setsid_bin" "$env_bin" "$bin" "$k" "$@" </dev/null >/dev/null 2>&1 9>&- &
  ) 9>"$ROOT/.ws/locks/apps" || exit $?
}

# Waits for app <n>'s window (or its exit) until APP_WAIT seconds after its start, and reports it.
app_wait() {
  n=$1
  restarted=$(cat "$APPS/$n.restarted" 2>/dev/null)
  [ "$restarted" = 1 ] || restarted=0
  st=$(cat "$APPS/$n.start" 2>/dev/null)
  is_uint "$st" || st=$(now_ms)
  deadline=$((st + APP_WAIT * 1000))
  pid=
  while :; do
    if [ -f "$APPS/$n.exit" ]; then
      printf 'WS ok exited %s\n' "$(cat "$APPS/$n.exit")"
      tail -c "$APP_LOG_START" "$APPS/$n.log" 2>/dev/null
      return 0
    fi
    valid_pid "$pid" || pid=$(cat "$APPS/$n.pid" 2>/dev/null)
    if valid_pid "$pid" && win=$(find_window "$n" "$pid" "$APPS/$n.before"); then
      echo "${win%% *}" >"$APPS/$n.win"
      printf 'WS ok app %s %s %s\n' "$pid" "$win" "$restarted"
      return 0
    fi
    [ "$(now_ms)" -lt "$deadline" ] || break
    sleep 0.2
  done
  valid_pid "$pid" || pid=-
  printf 'WS ok nowindow %s %s\n' "$pid" "$restarted"
  tail -c "$APP_LOG_START" "$APPS/$n.log" 2>/dev/null
}

# app-stop <n> [--force]: SIGTERM to the app's session (SIGKILL with --force), SIGKILL after 5 s.
# `WS ok stopped <code|-> <was running: 0|1>`, then the log's tail.
cmd_app_stop() {
  [ $# -ge 1 ] && [ $# -le 2 ] || die usage 2 "app-stop <n> [--force]"
  n=$1
  need_app "$n"
  force=0
  if [ $# -eq 2 ]; then
    [ "$2" = --force ] || die usage 2 "unknown argument $2"
    force=1
  fi
  was=0
  if [ ! -f "$APPS/$n.exit" ]; then
    was=1
    wait_file "$APPS/$n.pid" 2
    pid=$(cat "$APPS/$n.pid" 2>/dev/null)
    if valid_pid "$pid"; then
      sig=TERM
      [ "$force" = 1 ] && sig=KILL
      kill -"$sig" -- "-$pid" 2>/dev/null || kill -"$sig" "$pid" 2>/dev/null
      wait_file "$APPS/$n.exit" 5
      if [ ! -f "$APPS/$n.exit" ]; then
        kill -KILL -- "-$pid" 2>/dev/null || kill -KILL "$pid" 2>/dev/null
        wait_file "$APPS/$n.exit" 5
      fi
    elif [ ! -f "$APPS/$n.exit" ]; then
      # The wrapper never launched the app: record it as ended, so it stops counting as running.
      echo "ws: app $n has no pid; its wrapper did not start it" >>"$APPS/$n.log"
      echo 127 >"$APPS/$n.exit"
    fi
  fi
  printf 'WS ok stopped %s %s\n' "$(cat "$APPS/$n.exit" 2>/dev/null || echo -)" "$was"
  tail -c "$APP_LOG_STOP" "$APPS/$n.log" 2>/dev/null
}

# shot <n> <app|0> <max_edge> [--region <x> <y> <w> <h>]: the app's window (0: the only app, else the whole screen),
# the region cropped in window pixels, kept full size at .ws/shots/<n>.png. `WS ok shot <app|0> <window|root> <x> <y>
# <w> <h>` (the window's geometry on the screen), then the image fields and the image as `image` prints them.
cmd_shot() {
  [ $# -eq 3 ] || [ $# -eq 8 ] || die usage 2 "shot <n> <app|0> <max_edge> [--region <x> <y> <w> <h>]"
  n=$1; app=$2; m=$3
  is_pos "$n" || die usage 2 "call number must be a positive integer"
  is_uint "$app" || die usage 2 "app must be an integer"
  is_pos "$m" || die usage 2 "max_edge must be a positive integer"
  rx=0; ry=0; rw=; rh=
  if [ $# -eq 8 ]; then
    [ "$4" = --region ] || die usage 2 "unknown argument $4"
    rx=$5; ry=$6; rw=$7; rh=$8
    { is_uint "$rx" && is_uint "$ry" && is_pos "$rw" && is_pos "$rh"; } || die usage 2 "region must be x y >= 0 and w h >= 1"
  fi
  [ "$app" = 0 ] || need_app "$app"
  need_x
  x_up || die nodisplay 2 "the display is not running; app_start starts it again"
  if [ "$app" = 0 ]; then
    live=$(live_apps)
    [ -n "$live" ] && [ "$(echo "$live" | wc -l)" -eq 1 ] && app=$live
  fi
  if [ "$app" = 0 ]; then
    win=root
    g=$(win_geom -root) || die nodisplay 2 "cannot read the screen size"
  else
    if [ -f "$APPS/$app.exit" ]; then die exited 2 "app $app exited with code $(cat "$APPS/$app.exit")"; fi
    pid=$(cat "$APPS/$app.pid" 2>/dev/null)
    found=
    valid_pid "$pid" && { found=$(find_window "$app" "$pid") || found=; }
    if [ -z "$found" ]; then
      last=$(cat "$APPS/$app.win" 2>/dev/null)
      [ -n "$last" ] && g=$(win_geom "$last") && found="$last $g"
    fi
    [ -n "$found" ] || die nowindow 2 "app $app has no window on the display"
    win=${found%% *}; g=${found#* }
  fi
  read -r wx wy ww wh <<EOF
$g
EOF
  [ -n "$rw" ] || { rw=$ww; rh=$wh; }
  [ $((rx + rw)) -le "$ww" ] && [ $((ry + rh)) -le "$wh" ] || die region 2 "the region is outside the window (${ww}x${wh})"
  sg=$(win_geom -root) || die nodisplay 2 "cannot read the screen size"
  read -r _ _ sw sh <<EOF
$sg
EOF
  # The window's region as the screen shows it (menus and dialogs above it included), cut to the screen.
  x0=$((wx + rx)); y0=$((wy + ry)); x1=$((x0 + rw)); y1=$((y0 + rh))
  [ "$x0" -lt 0 ] && x0=0
  [ "$y0" -lt 0 ] && y0=0
  [ "$x1" -gt "$sw" ] && x1=$sw
  [ "$y1" -gt "$sh" ] && y1=$sh
  [ "$x1" -gt "$x0" ] && [ "$y1" -gt "$y0" ] || die region 2 "the region is off the screen"
  mkdir -p "$SHOTS" || die io 2 "cannot create $SHOTS"
  full=$SHOTS/$n.png
  tmp=$(new_tmp) || die io 2 "cannot write in $TMPD"
  if ! im_import -display "$DPY" -window root "png:$tmp" 2>/dev/null; then
    rm -f "$tmp"; die image 2 "cannot capture the screen (is ImageMagick installed?)"
  fi
  if [ "$x0" = 0 ] && [ "$y0" = 0 ] && [ "$x1" = "$sw" ] && [ "$y1" = "$sh" ]; then
    mv -f "$tmp" "$full" || { rm -f "$tmp"; die io 2 "cannot write $full"; }
  else
    im_convert "png:$tmp" -crop "$((x1 - x0))x$((y1 - y0))+$x0+$y0" +repage "png:$full" 2>/dev/null || { rm -f "$tmp"; die image 2 "cannot crop the screenshot"; }
    rm -f "$tmp"
  fi
  image_out "shot $app $win $wx $wy $ww $wh" "$full" "$m"
}

[ $# -ge 1 ] || die usage 2 "ws <init|run|status|kill|put|untar|read|image|cat|rg|app-start|app-stop|shot>"
sub=$1; shift
case $sub in
  init) cmd_init "$@" ;;
  run) cmd_run "$@" ;;
  status) cmd_status "$@" ;;
  kill) cmd_kill "$@" ;;
  put) cmd_put "$@" ;;
  untar) cmd_untar "$@" ;;
  read) cmd_read "$@" ;;
  image) cmd_image "$@" ;;
  cat) cmd_cat "$@" ;;
  rg) cmd_rg "$@" ;;
  app-start) cmd_app_start "$@" ;;
  app-stop) cmd_app_stop "$@" ;;
  shot) cmd_shot "$@" ;;
  *) die usage 2 "unknown subcommand $sub" ;;
esac
