#! /bin/sh

# time a make command, and log the output, surrounded by "date" calls

# a mail is sent with the tail of the log when the build is finished
# the build process is started in the background, and a tail -f is
# started on the logfile

usage ( ) {
    echo "usage: $0 [ -m ] -l <logfile> <command> ..."
    echo "  -m: disable mail sending"
    exit
}

# void command: do nothing
void () {
}

warn_left () {
    echo there might be some processes left running right now.
    echo their parent PID is $sub_pid
    read -p "Do you want to kill the process $sub_pid? [y/N]" yesno
    case $yesno in
    [Yy][Ee][Ss]|[Yy])
        echo "sending SIGHUP to $sub_pid"
        kill -HUP $sub_pid;;
    *)
        echo "leaving $sub_pid running";;
    esac
}

cleanup () {
    echo "killing process $pid"
    kill $pid
}

cli=$*

args=`getopt l:m $*`

if [ $? != 0 ] ; then
        usage
        exit 1
fi

set -- $args

for i; do
        case "$i" in
                -m)
                        mflag="void"; shift;;
                -l)
			logfile=$2; shift; shift;;
                --)
                        shift; break;;
        esac
done

if [ "X$logfile" = "X" ] ; then
	echo "-l parameter mandatory"
	usage
fi

if [ -f $logfile ] ; then 
	mv $logfile $logfile.old
fi

if [ $# -lt 1 ] ; then
	echo "$0: no command given"
	usage
fi

parent_pid=$$
# command is $* minus "--"
command=$*
command=${command#-- }

echo "Command: $command" > $logfile || usage

# start process and wait for mail in bkgnd
(
    trap "" HUP # ignore sighups here
    trap cleanup_sub INT
    # start process and wait for termination
    {
        echo -n "Starting date: "; date 
        time $command &
        pid=$!
        echo "Process id: $pid"
	# this keeps the exit status
        wait $pid || 
		(c=$?; echo command $command failed; exit $c)
	command_status=$?
        echo -n "End date: "; date
    } >> $logfile 2>&1 
    command_status=$?
    # process finished, send report
    {
        echo command:     $command
        echo exit status: $command_status
        echo directory:   $PWD
        echo 
        if [ -f $logfile ]; then 
            echo "head(1) and tail(1) of logfile follow"
            echo
            head $logfile
            echo "..."
            tail $logfile
        else
            echo "logfile not a regular file, not printed"
        fi
    } | $mflag mail -s "buildit report" ${LOGNAME:-$USER}
    exit $command_status
) &

sub_pid=$!

# see what we're doing
tail -f $logfile &
tail_pid=$!

# cleanup tail process when we loose terminal
trap "kill -HUP $tail_pid; exit 1" HUP
# prompt the user on interruption
trap warn_left INT TERM

wait $sub_pid
command_status=$?

kill -TERM $tail_pid
exit $command_status
