#!/bin/sh -

# runif - run the given command depending on a given (stateful) condition
# Steve Kinzler, steve@kinzler.com, Dec 20
# https://kinzler.com/me/home.html#unix

bad=
case "$#,$1" in
0,*|*,-h)	bad=t;;
*)	runme="$1"; shift
	case "$#,$1" in
	0,*)		cond=cmd; set cmd true;;
	*,cmd)		cond="$1";;
	3,after)	cond="$1"; tag="$2"; min="$3"
			echo "$tag" | perl -ne 'exit(! /^[-\w]+$/)' || bad=t
			echo "$min" | perl -ne 'exit(! /^\d+$/)'    || bad=t;;
	*)		bad=t;;
	esac; shift
esac

case "$bad" in
?*)	cat 1>&2 <<EOF
usage: $0 { command } cmd [ cond_command ]
Run command if cond_command is true.
usage: $0 { command } after { tag } { min }
Run command if more than min minutes have passed since the last run with
the given tag (or if it is the first run with the given tag).
EOF
	exit 1;;
esac

case "$cond" in
cmd)	eval "$@" && eval "$runme";;

after)	state="${TMPDIR:-/tmp}/runif-$tag"
	if test ! -e "$state" \
	     -o -n "`find $state -mmin +$min 2> /dev/null`"
	then
		: > "$state"
		eval "$runme"
	fi;;
esac
