#!/bin/bash -e

# Don Marti <dmarti@zgp.org>
# (If you need a license on this in order to use it,
# mail me and I'll put a license on it.  Otherwise,
# de minimis non curat lex.)

# re-run make, with the supplied arguments, when a
# Makefile prerequisite changes.  Example:
#   makewatch test

# Requires inotifywait.  Probably requires GNU Make to
# get the right "-dnr" output.  Not tested with other
# "make" implementations

ARGS=$*

wait_and_restart() {
    which cowsay &> /dev/null && \
    	cowsay "perhaps healthy habits will fix my Makefile" || \
	echo -n "an error happened, "
    sleep 2
    echo -n "restarting "
    echo $0 $ARGS
    exec $0 $ARGS
}
trap wait_and_restart ERR

make_prereqs() {
    # Make "make" list the files it's interested in.
    echo "Makefile"
    make -dnr $* | tr ' ' '\n' | \
        grep ".*'.$" | grep -o '\w.*\b'
}

prereq_files() {
    # prerequisites mentioned in a Makefile
    # that are extant files
    echo ' '
    for f in `make_prereqs $* | sort -u`; do
        [ -e $f ] && echo -n "$f ";
    done
    echo
}

time make $*
make -q $* || exec $0 $*

echo "make $* -- finished"

inotifywait -e close_write -e create -e delete_self \
	-e modify -e move -e move_self --quiet \
	$(prereq_files $*)
exec $0 $*

