#!/usr/bin/env bash

set -e

CLEAR=false
INTERVAL=""
CMD=""

# Parse arguments in any order
for ARG in "$@"; do
	if [ "$ARG" == "--clear" ]; then
		CLEAR=true
	elif [[ "$ARG" =~ ^[0-9]+$ ]] && [ -z "$INTERVAL" ]; then
		INTERVAL="$ARG"
	else
		CMD+="$ARG "
	fi
done

# Trim trailing space from CMD
CMD=$(echo "$CMD" | sed 's/ $//')

# Validate
if [ -z "$INTERVAL" ] || [ -z "$CMD" ]; then
	echo "Repeat any command at a set interval, with option to clear at each run."
	echo
	echo "Usage:"
	echo "  $0 [--clear] <interval_in_seconds> <command_in_quotes> (any order)"
	echo "Example:"
	echo "  $0 --clear 1 \"ls -l\""
	echo
	echo "The script parses through arguments for \'--clear\', a number, and the rest will be passed as a command."
	exit 1
fi

echo "Running command: $CMD every $INTERVAL second(s)..."
[ "$CLEAR" = true ] && echo "The screen will be cleared before each execution."
echo "Press Ctrl+C to stop."

# Infinite loop
while true; do
	[ "$CLEAR" = true ] && clear
	eval "$CMD"
	echo
	echo "Ctrl + C to stop"
	sleep "$INTERVAL"
done
