#!/bin/sh

# shellcheck disable=SC2249,SC2312

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

  RUN_COMMAND=
  COUNT=
  INTERVAL=0
  TIME=
}

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_COMMAND="$*"
}

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_COMMAND}" ]; then
    exit_error 'no command to run'
  fi
}

exit_error() {
  [ -z "$1" ] || echo "${COMMAND}: $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_COMMAND}"

    RUN_COUNT=$((RUN_COUNT + 1))

    [ -n "${TIME}" ] && [ "$(current_time_sec)" -ge "${END_TIME}" ] && return 0

    sleep "${INTERVAL}"
  done
}

init_variables
parse_command_line "$@"
validate_command_line

loop_command
