#!/bin/sh
set -eu

usage() {
	cat <<-'EOF'
		Usage:
		  n-times COUNT COMMAND...
		  n-times -h
	EOF
}

help() {
	cat <<-'EOF'


		Options:
		  -h, --help    show this message

		  COUNT         the number of times for COMMAND to be executed


		Run COMMAND, COUNT times.


		Examples:

		  Print 123 5 times:

		    $ n-times 5 echo 123
	EOF
}


for flag in "$@"; do
	case "$flag" in
		(--)
			break
			;;
		(--help)
			usage
			help
			exit
			;;
		(*)
			;;
	esac
done

while getopts 'h' flag; do
	case "$flag" in
		(h)
			usage
			help
			exit
			;;
		(*)
			usage >&2
			exit 2
			;;
	esac
done
shift $((OPTIND - 1))


COUNT="${1:-}"
shift

eval "$(assert-arg -- "$COUNT" 'COUNT')"


while true; do
	if [ "$COUNT" = 0 ]; then
		break
	fi
	COUNT=$((COUNT - 1))
	"$@"
done
