#!/bin/bash
#
# Master script to process autobench.dat
# removes top line from the file, executing if it is not a comment
# if the command returns, the next line of the file is read and
# executed util the file is exhausted.  
#
#
# If a config file is not specified, use the one in 
# $AUTODIR/scripts/autobench.dat  otherwise, use the one specified.
# Only $AUTODIR/scripts/autobench.dat will be restarted after a reboot. 
#
# optparam flag 1 Run once
# optparam flag "-j" value Specify the jobid, for log files, etc
# optparam flag "-m" Specify that autorun is being managed, and should not restart automatically after a reboot
# optparam value Path and filename of the .dat to process
#


. /etc/autobench.conf || . functions

cd $AUTODIR/scripts
mkdir -p $AUTODIR/var/run 2> /dev/null
STATUSFILE=$AUTODIR/var/run/status
STATUSPIPE=$AUTODIR/var/run/status-pipe
RUNFILE=$AUTODIR/var/run/running
MANAGEDFILE=$AUTODIR/var/run/managed
mknod $STATUSPIPE p 2> /dev/null
#flush out any prior state from status file
echo "running" > $STATUSFILE

function cleanup () {
    #remove config file since we are done with this dat file
	echo "Running cleanup"
    rm $CFGDIR/autobench.cfg &> /dev/null

    # remove the tmp file to store which profilers to use
    # FIXME -- This is the default profilers again...
    rm $TMPDIR/profilers 2> /dev/null
    rm $AUTODIR/scipts/startprofilers 2> /dev/null
    rm $AUTODIR/scipts/stopprofilers 2> /dev/null
    useprofiler sar 5
    useprofiler oprofile
    # clean up the jobid file
    rm $AUTODIR/var/run/jobid 2> /dev/null
    # clean up the runonce file
    rm $AUTODIR/var/run/runonce 2> /dev/null
    # clean up the running file
    rm $RUNFILE	2> /dev/null
    # clean out the user directory
    if [ -e $MANAGEDFILE ]; then
    	rm -r $AUTODIR/user 2> /dev/null
	    mkdir -p $AUTODIR/user/install
	fi
    # clean up the managed flag
    rm $MANAGEDFILE 2> /dev/null
    # clean up log file if it was created
    rm $LOGFILE 2> /dev/null
	#clean up console log if it exists
	rm $AUTODIR/logs/console_log 2>/dev/null
	rm -rf $AUTODIR/logs/default/* 2>/dev/null
    # clean up barrier directories
	rm -Rf $AUTODIR/var/tmp/barrier/* 2> /dev/null
	rm -f $AUTODIR/logs/autobench.dat
	cp $AUTODIR/scripts/autobench.dat $AUTODIR/logs/autobench.dat

}

function force_exit () {
	log " Fatal error, aborting autorun"
	echo "died" > $STATUSFILE
	if [ -e $MANAGEDFILE ]; then
		echo "quit_event: autobench_fail" > $STATUSPIPE
	fi
	if [ -n "$MACHINE_OWNER_MAIL" ]; then
		  FROM=$(hostname -s)
		  TEXT=$(tail -n50 $AUTODIR/logs/console_log)
          echo "$TEXT" | mail -s "Autobench error on $FROM, aborting"  $MACHINE_OWNER_MAIL
	fi
	exit 86
}

function normal_exit () {
	log "Normal exit from autorun, probably reboot"
	echo "exit" > $STATUSFILE
	exit 87
}

function force_exit_hup () {
	log "autorun got SIGINT, terminating"
	force_exit
}

trap force_exit_hup SIGINT;

while [ $# -gt 0 ]; do
    if [ "$1" = "1" ]; then
        RUNONCE=yes
		cleanup
        touch $AUTODIR/var/run/runonce
        shift
    elif [ "$1" = "-j" ]; then
        JOB_ID=$2
        shift 2
    elif [ "$1" = "-m" ]; then
        touch $AUTODIR/var/run/managed
        shift
    else
        CFGFILE=$1
        shift
    fi
done

if [ -e $AUTODIR/var/run/runonce ]; then
    RUNONCE=yes
fi

mkdir -p $NONTESTLOGDIR
export LOGFILE=$AUTODIR/logs/logfile
export TMPDIR=$AUTODIR/var/tmp/

log "log restarting autobench `date`"
CFGFILE=$AUTODIR/scripts/autobench.dat
CFGDIR=$AUTODIR/scripts

mkdir -p $TMPDIR

x=`pidof -x $AUTODIR/scripts/autorun`
count=`echo $x | awk '{print NF}'`
if [ "$count" -ge 2 ]
then 
    echo "autobench already running, exiting."
    exit
fi

#re-export any existing config
export_cfg
while last=`date`; do
    if [ -e $AUTODIR/sources/bin/dos2unix ]; then
        $AUTODIR/sources/bin/dos2unix -o autobench.dat &> /dev/null
    fi
    while [ -s $CFGFILE ] ; do

        echo "running" > $STATUSFILE
        echo "running" > $RUNFILE

        read cmdstr < $CFGFILE
        head -n 1 $CFGFILE >> $CFGFILE.done
        tail -n+2 $CFGFILE > $CFGFILE.new
        rm $CFGFILE
        mv $CFGFILE.new $CFGFILE

        #check for line starting with comment
        echo $cmdstr | grep '^#' > /dev/null
        if [ $? != 0 ]; then
            echo $cmdstr | grep '^+' > /dev/null
            if [ $? == 0 ]; then
                # skip the '+' symbol
                tmp=${cmdstr:1}
                # strip off trailing comment(s)
                tmp=${tmp%#*}
                # output alias to config file
                add_parm $tmp 2> /dev/null
                # If this .dat file was genereted on the GM
                # We can figure out who we are below
                if echo "$tmp" | grep -q '^\$hostIP_mine'; then
                    export MYIP=`echo $tmp | sed -e 's/^\$hostIP_mine *//'`
                fi
				#cfg has changed, re-export all vars for nesting
				export_cfg
            else
        		# do any necessary scriptmode processing
        		scriptmode_setup "$cmdstr"
        		if [ $? -eq 1 ]; then
        			continue
        		fi
                # expand command (replace aliases)
                cmdstr=`expand_command "$cmdstr"`

        		cmdstr_nospc="`echo "$cmdstr" | perl -p -e 's/\s*//g'`"
        		if [ -z "$cmdstr_nospc" ]; then
        			# empty line
        			continue;
        		fi;

                # try to install the command
                cmd=`echo "$cmdstr" | cut -f1 -d" "`
                getcommand $cmd
                exitcode=$?
                if [ $exitcode -eq 3 ]; then
                    echo "Warning: $cmd could not be installed -- using `which $cmd`"
                elif [ $exitcode -eq 2 ]; then
                    echo "Warning: $cmd could not be installed or found"
                fi
                                       
                #execute the command
                log "processing command: '$cmdstr'"
                echo "executing '$cmdstr'" > $STATUSFILE
                eval $cmdstr &
        		# signals are not handled until child precesses are done,
        		# except when that process is wait.
        		wait $!
        		RC=$?
                if [ $RC = "86" ]; then
        		    force_exit
        	    elif [ $RC = "87" ]; then
        			# we were told to just exit.  Probably rebooting
        			normal_exit
        		elif [ $RC -gt 128 ]; then
        			echo wait got a signal
                fi
			fi
        fi
    done  2>&1 | tee -a $AUTODIR/logs/console_log

	#add if to check for STATUS since new tee code causes sub-shell and
	# exit inside of loop to fail
	STATUS=$(head -n1 $STATUSFILE)
	if [ "$STATUS" == "exit" -o "$STATUS" == "died" ]; then
		rm $STATUSFILE
		exit 87
	fi
    echo "idle" > $STATUSFILE

    if [ -e $MANAGEDFILE ]; then
        echo "quit_event: autobench_done" > $STATUSPIPE
    fi

    # renumber previous autobench.dat.### files
    if [ -e autobench.dat.001 ]; then
        for file in $(ls -1r autobench.dat.???); do
            file=${file## *}
            mv $file ${file%.*}.$(echo ${file##*.} | awk '{printf "%03d", $1+1}')
        done
    fi
    if [ -e autobench.dat.done ] ; then
        mv autobench.dat.done autobench.dat.001
    fi

    # check if 1 time run asked for, if so exit
    if [ -n "$RUNONCE" ]; then
        rm $STATUSFILE
        exit
    fi

    # get the next dat file to process
    if ! (get_datfile `hostname -s`); then
        echo "Waiting 20 seconds for new work to appear......"
        sleep 20
	else 
		cleanup
    fi
done
exit
