#!/usr/bin/env bash

# Safer shell script with these options
# -e          : exit if a command exits with non-zero status
# -u          : exit if an expanded variable does not exist
# -o pipefail : if a command in a pipeline fail, fail the pipeline
#               (e.g this now fails: false | true)
set -euo pipefail

# Invert the return value of a program, always works, even in some cases
# where `!` is not recognized as a bash builtin.
# (e.g: when saving it to an array and running the whole cmd)
function not() {
  if "$@"; then
    false # worked, invert result to false
  else
    true # failed, invert result to true
  fi
}

function usage() {
  local ctrl_mode="$1"; shift # The internal mode (while or until)
  echo "Usage: repeat_every_$ctrl_mode <interval> [--sep|--compact-sep] <cmd...>"
}

function repeat_every_impl() {
  local ctrl_mode="$1"; shift # The internal mode (while or until)

  if [[ $# == 0 ]]; then
    usage "$ctrl_mode"; return 1
  fi

  # TODO: add '--rand 5-15' interval option (random between 5 and 15 seconds)
  local interval="$1"; shift

  # TODO: add --bell support when script ends
  # TODO: allow `--` before command for clarity

  # FIXME(not here): Add support to shell aliases (must be done in shell config)

  local use_separator=false
  local use_compact_separator=false
  if [[ "${1:-}" == "--sep" ]]; then
    use_separator=true
    shift
  fi
  if [[ "${1:-}" == "--compact-sep" ]]; then
    use_separator=true
    use_compact_separator=true
    shift
  fi
  local cmd=("$@")

  if [[ "${#cmd[@]}" == 0 ]]; then
    usage "$ctrl_mode" && return 1
  fi

  local run_comment
  if [[ "$ctrl_mode" == "until" ]]; then
    run_comment="failed (expecting success)"
    # Instead of changing the control structure from while to until, we change the condition.
    # We can't use '!' to invert the return here, bash does not recognize '!' as a builting then..
    cmd=(not "${cmd[@]}")
  else
    run_comment="succeeded (expecting failure)"
  fi

  local run_count=0
  local now
  while "${cmd[@]}"; do
    run_count=$(( run_count + 1 ))
    if $use_separator; then
      $use_compact_separator || echo
      now=$(date +%T) # hour:min:sec
      echo "--- [repeat_every_$ctrl_mode $now] Last run (n°$run_count) $run_comment, re-running in ${interval}s ---"
      $use_compact_separator || echo
    fi
    sleep $interval
  done
}

case "$(basename $0)" in
  repeat_every_while)
    repeat_every_impl "while" "$@";;
  repeat_while)
    repeat_every_impl "while" 1 "$@";;
  repeat_every_until)
    repeat_every_impl "until" "$@";;
  repeat_until)
    repeat_every_impl "until" 1 "$@";;
  *)
    2>&1 echo "Unknown binary alias, known ones:"
    2>&1 echo "  repeat_every_while"
    2>&1 echo "  repeat_every_until"
    2>&1 echo "  repeat_while"
    2>&1 echo "  repeat_until"
    exit 1
    ;;
esac

# vim:set sw=2:
