#!/bin/sh
# Starts Kiri's engine: when WSL boots the distro (wsl.conf), after setup,
# when kiri-win starts, and when `kiri bridge` finds no daemon on its socket.
# The daemon serves its unix socket; kiri-win carries the Windows docker CLI
# to it over `kiri bridge`. `--restart` (kiri-win's Restart engine) stops the
# daemon first. Exit 0: it runs; 1: no socket in time (it may still come
# up), or the old one did not stop; 2: it exited as it started.
export HOME=/var/lib/kiri-daemon
sock=$HOME/.kiri/run/docker.sock
mounts=${KIRI_PROC_MOUNTS:-/proc/mounts}
ro_state=$(awk '
  BEGIN { l1 = 0; l2 = 0; k1 = 0; k2 = 0 }
  function covers(mp, t) { return mp == "/" || t == mp || index(t, mp "/") == 1 }
  function ro(opts,   a, n, i, r) {
    n = split(opts, a, ","); r = 0
    for (i = 1; i <= n; i++) {
      if (a[i] == "emergency_ro") return 2
      if (a[i] == "ro") r = 1
    }
    return r
  }
  NF >= 4 {
    mp = $2; if (length(mp) > 1) sub("[/]+$", "", mp)
    if (covers(mp, "/") && length(mp) >= l1) { l1 = length(mp); k1 = ro($4) }
    if (covers(mp, "/var/lib/kiri") && length(mp) >= l2) { l2 = length(mp); k2 = ro($4) }
  }
  END {
    if (k1 == 2 || k2 == 2) print "was remounted read-only by Linux (emergency_ro)"
    else if (k1 > 0 || k2 > 0) print "is mounted read-only (emergency_ro)"
  }
' "$mounts" 2>/dev/null)
if [ -n "$ro_state" ]; then
  echo "Kiri's WSL2 disk (ext4.vhdx) $ro_state after an unclean shutdown or filesystem error. To recover: 1) run 'wsl --shutdown' in PowerShell; 2) attach the disk bare with 'wsl --mount <path>/ext4.vhdx --vhd --bare' (default %LOCALAPPDATA%/Kiri/wsl/kiri/ext4.vhdx); 3) from another Linux distro in WSL, find the device with 'lsblk' and run 'sudo e2fsck -f -y -D /dev/<disk>', then 'wsl --unmount'; or move/recreate storage in Settings -> Storage." >&2
  exit 2
fi
mkdir -p "$HOME" /var/log
# Clear an empty /etc/localtime or /etc/timezone directory left by pre-fix
# `-v` bind mounts before the daemon starts and restores valid files (#938).
[ -d /etc/localtime ] && [ ! -L /etc/localtime ] && rmdir /etc/localtime 2>/dev/null || true
[ -d /etc/timezone ] && [ ! -L /etc/timezone ] && rmdir /etc/timezone 2>/dev/null || true
# One at a time: the boot command, the bridge, kiri-win and `kiri`
# (crates/kiri/src/wsl.rs) can each start it at once, and two would each
# remove the socket and start a daemon. busybox flock has no time limit of
# its own: -n, tried for 25 s. A plain kiri-start holds it at most 20 s, so
# one waiting behind it gets it, and finds the daemon it started; the
# bridge gives a start 25 s, enough for that. One that waits on a
# --restart gives up, and the restart starts the daemon.
exec 9>"$HOME/.kiri-start.lock"
i=0
until flock -n 9; do
  [ "$i" -ge 250 ] && { echo "another kiri-start has not finished in 25 s" >&2; exit 1; }
  sleep 0.1
  i=$((i + 1))
done
running() { pgrep -f '/usr/local/bin/kiri daemon' >/dev/null 2>&1; }
# On SIGTERM the daemon removes its socket, then stops its containers
# (seconds; ~10 s for one that ignores SIGTERM, up to 120 s for one with a
# long --stop-timeout: SHUTDOWN_WAIT_CAP, then 2 s after SIGKILL), powers
# off its VM (up to 10 s), then exits: about 132 s at most. --restart waits
# 140 s for that.
if [ "${1:-}" = --restart ] && running; then
  pkill -f '/usr/local/bin/kiri daemon'
  i=0
  while running; do
    [ "$i" -ge 1400 ] && { echo "the kiri daemon did not stop in 140 s; see /var/log/kiri.log" >&2; exit 1; }
    sleep 0.1
    i=$((i + 1))
  done
fi
# A daemon with its socket runs. One without is starting (its socket
# comes) or stopping (it is gone soon, and one is started here): up to 15 s.
i=0
while running; do
  [ -S "$sock" ] && exit 0
  [ "$i" -ge 150 ] && { echo "a kiri daemon runs without its socket for 15 s; see /var/log/kiri.log" >&2; exit 1; }
  sleep 0.1
  i=$((i + 1))
done
rm -f "$sock"
# WSL ships x86 KVM as modules; without udev nothing loads the CPU driver.
if [ ! -c /dev/kvm ]; then
  if grep -qw vmx /proc/cpuinfo; then modprobe -q kvm_intel 9>&- 2>/dev/null || true
  elif grep -qw svm /proc/cpuinfo; then modprobe -q kvm_amd 9>&- 2>/dev/null || true
  fi
fi
# The daemon does not keep the lock (fd 9).
nohup /usr/local/bin/kiri daemon >>/var/log/kiri.log 2>&1 9>&- &
pid=$!
i=0
while [ "$i" -lt 50 ]; do
  # Exit 2: it cannot start, and kiri-win need not wait for it. Checked
  # before the socket so a daemon that binds its socket and exits is not
  # treated as running.
  kill -0 "$pid" 2>/dev/null || { rm -f "$sock"; echo "kiri daemon exited as it started; see /var/log/kiri.log" >&2; exit 2; }
  [ -S "$sock" ] && exit 0
  sleep 0.1
  i=$((i + 1))
done
# Exit 1: it may still come up (a slow disk).
echo "kiri daemon did not create its socket in 5 s; see /var/log/kiri.log" >&2
exit 1
