#!/usr/bin/env sh
#
#/ wait_on - runs a given command in loop with a 5s delay between each execution
#/ if exit code is > 5 or < 1, then it halts and says "task is done"
#/
#/ Usage: wait_on [long-running-script]
#
# ---
# source: https://github.com/parkr/dotfiles/blob/main/bin/wait_on

# print help/usage with no pattern/args
test "$#" -eq 0 || test "$1" = "-h" || test "$1" = "--help" && {
  grep "^#/" "$0" | cut -c 4-
  printf '\n'
  exit 0
}

now=$(date "+%Y-%m-%dT%H:%M:%S")
while true; do
  "$@"
  code="$?"
  test -n "${DEBUG-}" && echo "code=${code}"
  if [ "${code}" -gt 5 ] || [ "${code}" -lt 1 ]; then
    break
  fi
  echo "---> (above printed at ${now})"
  sleep 5
done
say -v Karen "task is done."
