#!/usr/bin/env bash
# onchange -- run a command whenever a file is changed

. lib.bash || exit

usage() {
	echo "Usage: $progname <path>... -- <command>"
}

paths=()
cmd=()

while getopts : OPT; do
	case $OPT in
	*) lib:die_getopts;;
	esac
done; shift $((OPTIND-1))

argstate=0
for arg; do
	if (( argstate == 0 )); then
		if [[ $arg == -- ]]; then
			argstate=1
		else
			paths+=("$arg")
		fi
	else
		cmd+=("$arg")
	fi
done

if (( ! ${#paths[@]} )); then
	vdie "No files specified"
fi

if (( ! ${#cmd[@]} )); then
	cmd=(make)
elif (( ${#cmd[@]} == 1 )) && [[ $cmd = *\ * ]]; then
	cmd=(sh -c "$cmd")
fi

vmsg "Will monitor ${#paths[@]} files and run ${cmd[*]@Q}"

inotifywait -q -m -e close_write -- "${paths[@]}" |
	while read -r ev; do
		echo "Event: $ev"
		"${cmd[@]}" || warn "Command failed with status $?"
	done