#!/bin/bash

function timereport() {
	STARTTIME=$1
	ENDTIME=$2
    SECONDSPERMIN=60
    SECONDSPERHOUR=`expr 60 \* 60`
    SECONDSPERDAY=`expr 60 \* 60 \* 24`
    SECONDSPERYEAR=`expr 60 \* 60 \* 24 \* 365`
    ELAPSEDTIME=`expr $ENDTIME - $STARTTIME`
    YEARS=`expr $ELAPSEDTIME / $SECONDSPERYEAR`
    ELAPSEDTIME=`expr $ELAPSEDTIME % $SECONDSPERYEAR`
    DAYS=`expr $ELAPSEDTIME / $SECONDSPERDAY`
    ELAPSEDTIME=`expr $ELAPSEDTIME % $SECONDSPERDAY`
    HOURS=`expr $ELAPSEDTIME / $SECONDSPERHOUR`
    ELAPSEDTIME=`expr $ELAPSEDTIME % $SECONDSPERHOUR`
    MINUTES=`expr $ELAPSEDTIME / $SECONDSPERMIN`
    ELAPSEDTIME=`expr $ELAPSEDTIME % $SECONDSPERMIN`
	echo "Time Elapsed: $YEARS Years, $DAYS Days, $HOURS Hours, $MINUTES Minutes, $ELAPSEDTIME Seconds"
}

function diskreport() {
	SIGN=""
	DISKUSAGE=`expr $2 - $1`
	if [ $DISKUSAGE -lt 0 ]
	then
	    DISKUSAGE=`expr $DISKUSAGE '*' -1`
        SIGN='-'
    fi
	DISKUSAGE_INT=`expr $DISKUSAGE / 1024`
	DISKUSAGE_FRAC=`expr $DISKUSAGE % 1024`
    echo "Disk usage: $SIGN$DISKUSAGE_INT.$DISKUSAGE_FRAC Mb"
}

function instrument_command() {
    STARTDISK=`df -k . | grep --invert-match '^Filesystem' | awk '{print $3;}'`
	df -k .
	STARTTIME=`date +%s`
    (exec $*)
    ENDTIME=`date +%s`
    ENDDISK=`df -k . | grep --invert-match '^Filesystem' | awk '{print $3;}'`
	df -k .
	timereport $STARTTIME $ENDTIME
    diskreport $STARTDISK $ENDDISK
}

function xterm_title () {
    local working_directory
    if [ -z "$PWD" ]
    then
        working_directory=`/bin/pwd`
    else
        working_directory="$PWD"
    fi
    if [ "$1" == --title ]
    then
        shift
        title="$1"
        shift
    else
        title="$* @ `hostname`.`dnsdomainname`:$working_directory"
    fi
    echo ']0;'"$title"''
    if [ ! -z "$1" ]
    then
       "$@"
    fi
}


DONE=NO
USING_XTERM=`expr "$TERM" : "xterm.*"`
while [ "$DONE" = NO ] ; do
    case "$1" in
    --no-x)
        USING_XTERM=0
        shift
        ;;
    *)
        DONE=YES
        ;;
    esac
done

if [ $USING_XTERM -gt 0 ]
then
    xterm_title --title "build.3dfx $@ (RUNNING) @ `hostname --fqdn`:$PWD"
fi
instrument_command make -f makefile.autoconf "$@" 2>&1
retstat="$?"
if test "$retstat" = 0 ; then
    RETVAL="DONE"
else
    RETVAL="FAILED"
fi
if [ $USING_XTERM -gt 0 ]
then
    xterm_title --title "build.3dfx $@ ($RETVAL) @ `hostname --fqdn`:$PWD"
fi
exit $retstat
