#!/usr/bin/env sh
#
# rerun2 - events that occur within this time from an initial one are ignored
#
# ---
# source: https://github.com/tartley/rerun2

cooldown_s='0.250'
clear=''
verbose=''

# check dependencies
if ! command -v inotifywait >/dev/null; then
  echo "error: inotifywait: command not found. hint: install inotify-tools"
  exit 1
fi

usage() {
  echo "Rerun a given command every time filesystem changes are detected."
  echo ""
  echo "Usage: $(basename "$0") [OPTIONS] COMMAND"
  echo ""
  echo "  -c, --clear     Clear the screen before each execution of COMMAND."
  echo "  -v, --verbose   Print the name of the files that changed to cause"
  echo "                  each execution of COMMAND."
  echo "  -h, --help      Display this help and exit."
  echo ""
  echo "Run the given COMMAND, and then every time filesystem changes are"
  echo "detected in or below the current directory, run COMMAND again."
  echo "Changes within ${cooldown_s} seconds are grouped into one."
  echo ""
  echo "This is useful for running commands to regenerate visual output every"
  echo "time you hit [save] in your editor. For example, re-run tests, or"
  echo "refresh markdown or graphviz rendering."
  echo ""
  echo "COMMAND can only be a simple command, i.e. \"executable arg arg...\"."
  echo "For compound commands, use:"
  echo ""
  echo "    rerun bash -c \"ls -l | grep ^d\""
  echo ""
  echo "Using this it's pretty easy to rig up ad-hoc GUI apps on the fly."
  echo "For example, every time you save a .dot file from the comfort of"
  echo "your favourite editor, rerun can execute GraphViz to render it to"
  echo "SVG, and refresh whatever GUI program you use to view that SVG."
  echo ""
  echo "COMMAND can't be a shell alias, and I don't understand why not."
}

while [ $# -gt 0 ]; do
  case "$1" in
    -c | --clear)
      clear='1'
      ;;
    -v | --verbose)
      verbose='1'
      ;;
    -h | --help)
      usage
      exit
      ;;
    *)
      break
      ;;
  esac
  shift
done

execute() {
  [ -n "${clear}" ] && clear
  [ -n "${verbose}" ] && echo "$@"
  "$@"
}

execute "$@"
end_of_cooldown="$(date +%s%N)"
cooldown_ns="$(LC_ALL=C printf '%0.9f' "${cooldown_s}" | sed -r -e 's|\.||' -e 's|^0+||')"

inotifywait --quiet --recursive --monitor --format '%e %w%f' \
  --event='modify,close_write,move,create,delete' \
  --exclude='\.git|\..*\.swp|__pycache__|\.cache|\.pytest_cache' \
  . | while read -r changed; do

  now="$(date +%s%N)"
  if [ "${now}" -gt "${end_of_cooldown}" ]; then
    end_of_cooldown="$((now + cooldown_ns))"
    (sleep "${cooldown_s}" && execute "$@") &
  fi

  if [ -n "${verbose}" ]; then
    echo "${changed}"
  fi

done
