#!/bin/bash

# HERE BEGINS THE SCRIPT
SCRIPTNAME=$(basename $0)
SCRIPTBASE=$(dirname $0)/..
#make SCRIPTBASE fully qualified
SCRIPTBASE=$( cd $SCRIPTBASE && pwd )

source $SCRIPTBASE/bin/env.sh

# define reference directory that contains results
REFDIR=$SCRIPTBASE/test/ref/

# Just do a simple log to get traces
echo "$(date) : $SCRIPTNAME starts" >> $SCRIPTBASE/log/yoga.log

storeInfo(){
    echo "$*" >> test.info
    echo "$*"
}

usage(){
 echo "Usage: $(basename $0) [-h] [-d]"
 echo "  -d : change diff style"
 echo "  -k : do not remove temporary directory after loop"
 echo "  -h : show this message"
 echo "Reference dir is '$REFDIR', if you remove it, the program will store results as new references"
}

# parse cmd line
while getopts "dhk" option
do
    case $option in
        h )
        usage && exit ;;
        k ) 
        DEBUGMODE="-y" ;;
        d ) 
        DIFFOPTION="-y" ;;
        * ) # Unknown option
        usage && exit ;;
    esac
done


# creating one working area
TMPDIR=$SCRIPTBASE/tmp
if ! WORKING_DIRECTORY=$(mktemp -d)
then
    echo "ERROR: can't create working directory"
    echo "DEBUG: EXITING"
    exit 1
fi

if test -n "$DEBUGMODE"
then
  echo "Output is generated into $WORKING_DIRECTORY"
else
  trap "rm -rf $WORKING_DIRECTORY" 0 1 2 5 15
fi

echo "DEBUG: WORKING DIRECTORY is $WORKING_DIRECTORY"
cd $WORKING_DIRECTORY


# Generate Test informations
storeInfo "Test informations"
storeInfo 
storeInfo "Yorick version:"
storeInfo "$(echo quit | yorick )"
storeInfo 
storeInfo 


# Copy every xml/*data.xml input files
for f in $SCRIPTBASE/xml/*data.xml
do 
    cp $f .
done

# Check ref directory
if [ ! -d $REFDIR ]
then
   mkdir -p $REFDIR
   echo "DEBUG: ref dir created" 
fi


# Run test on every xml/*data.xml input files
for f in ./*data.xml
do 
    RESULTFILE="Res$(basename $f)"
    storeInfo "runFit for $f "
    $SCRIPTBASE/bin/runFit.sh  $f | awk '{if ($1=="END_XML_RESULT")end=1;if(start==1&&end!=1)print;if($1=="START_XML_RESULT")start=1;}' &> $RESULTFILE

    REFFILE=$REFDIR/$RESULTFILE
    if test -e $REFFILE
    then
        if DIFFRES=$(diff $DIFFOPTION $REFFILE $RESULTFILE)
        then
            storeInfo "Seems ok "
        else
            storeInfo "Diffing $REFFILE $RESULTFILE"
            storeInfo "$DIFFRES"
        fi
    else
        storeInfo "    Missing reference: this output will be ref"
        cp $RESULTFILE $REFFILE
    fi
done

# HERE ENDS THE SCRIPT
echo "$(date) : $SCRIPTNAME stops" >> $SCRIPTBASE/log/yoga.log
echo "DEBUG: WORKING DIRECTORY is $WORKING_DIRECTORY"
echo "DEBUG: REFERENCE DIRECTORY is $REFDIR"
exit 0
