#!/usr/bin/env bash
# Host side of the console's --restart-build grant (want file); logs host RAM every 10 s.
D=$HOME/q5055; cur=
# The console (uid 10001 in its container) asks through req/, which is world-writable.
mkdir -p $D/req && chmod 1777 $D/req && rm -f $D/req/want
while true; do
  want=$(cat $D/req/want 2>/dev/null || cat $D/want 2>/dev/null)
  if [ -n "$want" ] && [ "$want" != "$cur" ]; then
    echo "$(date +%T) switching to $want"
    docker rm -f q5055-engine >/dev/null 2>&1
    n=$(ls $D/logs/engine-$want-*.log 2>/dev/null | wc -l)
    setsid nohup $D/boot.sh "$want" > $D/logs/engine-$want-$n.log 2>&1 < /dev/null &
    cur=$want
  fi
  [ -f $D/stop ] && { docker rm -f q5055-engine q5055-console >/dev/null 2>&1; exit 0; }
  echo "$(date +%T) $(grep -E '^(MemAvailable|SwapFree|Mlocked)' /proc/meminfo | tr -s ' ' | tr '\n' ' ')" >> $D/logs/mem.log
  sleep 10
done
