#! /bin/sh
source="$1"
runid="S6"
if [ -f $DMTPARS/RunID ]; then
    runid=`cat $DMTPARS/RunID`
fi
archive="/archive/frames/$runid/L0/$LIGOSITE"
errFile="$DMTHTMLOUT/dvErr.log"
tWait=60
tAlarm=`expr $tWait + 10`
node=`uname -n`

if [ `Alarm getdefined CheckDataValid | grep -c CheckDataValid` ]; then
    Alarm define CheckDataValid Error \
	  -desc 'Daq Error: $1 dataValid errors found in $2' \
	  -flags 4 -time $tAlarm -sever 3 \
	  > /dev/null
    Alarm define CheckDataValid NoArchive \
	  -desc 'Daq Error: archive $1 not available on $2' \
	  -flags 4 -time $tAlarm -sever 3 \
	  > /dev/null
fi

# --- Look for an exclude file
if [ -f "$DMTPARS/DataValidExclude_${node}.txt" ]; then
    exclude="$DMTPARS/DataValidExclude_${node}.txt";
elif  [ -f "$DMTPARS/DataValidExclude_${source}.txt" ]; then
    exclude="$DMTPARS/DataValidExclude_${source}.txt"
elif  [ -f "$DMTPARS/DataValidExclude.txt" ]; then
    exclude="$DMTPARS/DataValidExclude.txt"
else
    exclude=""
fi

# --- Start loop over epochs
while ( sleep $tWait ) ; do

# --- Decide where the data are comming from.
    case "$source" in
	"archive") {
	    if [ -d "$archive" ]; then
		ldir=`ls -1 $archive | grep -- -R- | tail -1`
		lfil=`ls -1 $archive/$ldir/*.gwf | tail -1`
		input="-infile $lfil"
		echo "dataValid Errors from frame: $lfil" > $errFile
	    else
		Alarm set CheckDataValid NoArchive -params "$archive $node" \
		          -sever 3 -time $tAlarm \
		    > /dev/null
		input=""
	    fi
	} ;;
	"online") {
       	    input="-partition $LIGOSMPART"
	    echo "dataValid Errors from partition: $LIGOSMPART" > $errFile
	} ;;
	"*") {
	    input="-infile $source"
	    echo "dataValid Errors from frame: $source" > $errFile
	} ;;
    esac

# ---  Filter out the usual suspects (if requested)
    if [ -z "$input" ]; then
	echo "Archive $archive not available" > $errFile
    elif [ -n "$exclude" ]; then
	echo "Errors in file $exclude (`cat $exclude|wc -l` lines) excluded." \
	    >> $errFile
	FrTest -daqerr -maxframes 1 $input \
	    | fgrep -v -f $exclude >> $errFile 
    else
	FrTest -daqerr -maxframes 1 $input >> $errFile
    fi

# ---  Count the remaining channels and generate an alarm if
    errcnt=`grep -c "Daq error" $errFile`

    if [ $errcnt != 0 ] ; then
	Alarm set CheckDataValid Error -params "$errcnt $source" \
	          -sever 3 -time $tAlarm \
	    > /dev/null
    fi

done
