#!/bin/sh

init_variables() {
  progname=${0##*/}

  run_prog=
  count=
  interval=0
  time=
}

# shellcheck disable=SC2249
parse_command_line() {
  while getopts c:i:t: opt; do
    case "${opt}" in
      c) count="${OPTARG}" ;;
      i) interval="${OPTARG}" ;;
      t) time="${OPTARG}" ;;
      ?) exit_error ;;
    esac
  done

  shift "$((OPTIND - 1))"

  run_prog="$*"
}

# shellcheck disable=SC2249
validate_command_line() {
  if [ -z "${count}" ] && [ -z "${time}" ]; then
    exit_error 'you must specify at least -c or -t options'
  fi

  case "${count}" in
    *[!0-9]*) exit_error 'count must be an integer' ;;
  esac

  case "${time}" in
    *[!0-9]*) exit_error 'time must be an integer' ;;
  esac

  case "${interval}" in
    *[!0-9.]*) exit_error 'interval must be an number' ;;
  esac

  if [ -z "${run_prog}" ]; then
    exit_error 'no command to run'
  fi
}

exit_error() {
  [ -z "$1" ] || echo "${progname}: $1"
  exit 1
} >&2

current_time_sec() {
  # values with leading 0 are interpreted as octals
  # which leads to issue with "08" and "09"
  cur_hours=$(date +%H)
  cur_minutes=$(date +%M)
  cur_seconds=$(date +%S)
  echo $((\
  ${cur_hours#0} * 3600 + ${cur_minutes#0} * 60 + ${cur_seconds#0}))
}

loop_command() {
  [ -n "${time}" ] && end_time=$(($(current_time_sec) + time))

  run_count=1

  while true; do
    [ -n "${count}" ] && [ "${run_count}" -gt "${count}" ] && return 0

    i="${run_count}" eval "${run_prog}"

    run_count=$((run_count + 1))

    # shellcheck disable=SC2312
    [ -n "${time}" ] && [ "$(current_time_sec)" -ge "${end_time}" ] && return 0

    sleep "${interval}"
  done
}

init_variables
parse_command_line "$@"
validate_command_line

loop_command
