#!/bin/sh
# Installs or removes the fseventsd guard (fseventsd-guard.sh and README.md beside this file), as root, once per Mac.
# A person runs it; nothing in supercode does.
#
#   sudo /bin/sh fseventsd-guard-install.sh [critMB]     install: the guard restarts fseventsd past this many MB
#                                                        (256; a whole number from 64 to 65536)
#   sudo /bin/sh fseventsd-guard-install.sh uninstall    remove it (its log of restarts is left)
#
# Installed: /Library/dev.volter.supercode-health/fseventsd-guard.sh (root:wheel 0755, in a root:wheel 0755 directory)
# and /Library/LaunchDaemons/dev.volter.supercode-health.fseventsd-guard.plist (root:wheel 0644), which runs the
# installed copy every five minutes. Nothing installed refers back to this file's directory.
PATH=/usr/bin:/bin:/usr/sbin:/sbin; export PATH
LC_ALL=C; export LC_ALL
umask 022
set -eu

LABEL=dev.volter.supercode-health.fseventsd-guard
DIR=/Library/dev.volter.supercode-health
PLIST=/Library/LaunchDaemons/$LABEL.plist
die() { printf '%s\n' "fseventsd-guard-install: $1" >&2; exit 1; }
# owned by root, writable by nobody else, and with no access list that could grant it
rootonly() {
  case "$(ls -ld -- "$1")" in ??????????+*) return 1 ;; esac
  case "$(stat -f '%u %Lp' -- "$1")" in '0 '*[2367] | '0 '*[2367]?) return 1 ;; '0 '*) return 0 ;; *) return 1 ;; esac
}
loaded() {
  observation=$(/bin/sh "$src/launchctl-print.sh" "system/$LABEL" 2> "$capture/stderr")
  observed=$?
  if [ ! -s "$capture/stderr" ]; then
    case $observed in
      0) return 0 ;;
      113) [ -z "$observation" ] && return 113 ;;
    esac
  fi
  cat "$capture/stderr" >&2
  return 1
}
# the job is gone once launchd no longer knows it: a load while the old one is still leaving fails
unload() {
  if loaded; then :; else observed=$?; [ "$observed" -eq 113 ] && return 0; return 1; fi
  launchctl bootout "system/$LABEL" > /dev/null 2>&1 || true
  n=0
  while :; do
    if loaded; then
      [ "$n" -lt 10 ] || return 1
      sleep 1; n=$((n + 1))
    else
      observed=$?
      [ "$observed" -eq 113 ] && return 0
      return 1
    fi
  done
}

[ "$(uname -s)" = Darwin ] || die 'macOS only'
[ "$(id -u)" = 0 ] || die 'run it with sudo'
capture=$(mktemp -d /tmp/volter-guard-install.XXXXXXXX) || die 'cannot capture native output'
trap 'rm -rf "$capture"' 0
trap 'exit 1' 1 2 15
src=$(cd -- "$(dirname -- "$0")" && pwd)
[ -f "$src/launchctl-print.sh" ] || die "launchctl-print.sh is not beside this file ($src)"

if [ "${1:-}" = uninstall ]; then
  unload || die "could not confirm system/$LABEL is absent; nothing was removed"
  rm -f "$PLIST" "$DIR/fseventsd-guard.sh" "$DIR/launchctl-print.sh" "$DIR/fseventsd-guard.state" "$DIR/fseventsd-guard.last" "$DIR/fseventsd-guard.err" "$DIR/fseventsd-guard.read"
  printf '%s\n' "removed the fseventsd guard (its log stays: $DIR/fseventsd-guard.log)"
  exit 0
fi

crit=${1:-256}
case $crit in ''|*[!0-9]*|??????*) die 'the line is a whole number of MB from 64 to 65536' ;; esac
{ [ "$crit" -ge 64 ] && [ "$crit" -le 65536 ]; } || die 'the line is a whole number of MB from 64 to 65536'
[ -f "$src/fseventsd-guard.sh" ] || die "fseventsd-guard.sh is not beside this file ($src)"
for dir in /Library /Library/LaunchDaemons; do rootonly "$dir" || die "$dir is not root's alone to write: not installing a root job under it"; done

install -d -o root -g wheel -m 0755 "$DIR"
rootonly "$DIR" || die "$DIR is not root's alone to write"
install -o root -g wheel -m 0755 "$src/fseventsd-guard.sh" "$DIR/fseventsd-guard.sh"
install -o root -g wheel -m 0755 "$src/launchctl-print.sh" "$DIR/launchctl-print.sh"
cat > "$PLIST.tmp" <<PLIST
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
  <key>Label</key><string>$LABEL</string>
  <key>ProgramArguments</key>
  <array>
    <string>/bin/sh</string>
    <string>$DIR/fseventsd-guard.sh</string>
    <string>$crit</string>
  </array>
  <key>StartInterval</key><integer>300</integer>
  <key>RunAtLoad</key><true/>
  <key>ProcessType</key><string>Background</string>
  <key>StandardErrorPath</key><string>$DIR/fseventsd-guard.err</string>
</dict>
</plist>
PLIST
chown root:wheel "$PLIST.tmp"
chmod 0644 "$PLIST.tmp"
mv -f "$PLIST.tmp" "$PLIST"
unload || die "could not confirm the old system/$LABEL is absent; the new files are in place but not loaded: run this again"
launchctl bootstrap system "$PLIST" || die "launchd did not load $PLIST; the files are in place but the guard is NOT running: run this again"
loaded || die "launchd did not confirm system/$LABEL after loading it; the guard is NOT running"
printf '%s\n' "installed the fseventsd guard: it restarts fseventsd once it has logged \"event table has grown too large\" and holds over $crit MB; read it with: supercode health status"
