#!/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
usage()
{
    echoPre "\nUsage:\n $(basename $0) -s xmlDescriptorFile.xml [ITMAX=xx]\n"   
    echoPre "\n  -s : skip yoga result for the response, return only params and user_info"
}


# Store full path of INPUTFILE if given path was not absolute
INPUTFILE=$1
if test ${INPUTFILE:0:1} != "/" 
then
    INPUTFILE=$PWD/$1
fi
shift 1

DEFAULT_CHI2_MODE=slice
CHI2_MODE=$DEFAULT_CHI2_MODE

# Handle options of command line
# we can have numerical negative values that should not be hanlded has options
# ( do not exit in * case )
while getopts "hs" option
do
    case $option in
        s ) useYogaB64File="no" ;;
        h ) usage ; exit ; shift ;;
#        * ) usage ; exit 1 ;;
    esac
done
shift $(($OPTIND - 1))

# use ITMax and more as param for future yorick call
if test $# -ge 1
then
    INPUTARGS=,"$*"
else
    INPUTARGS=""
fi

echo "<response>"
trap beforeExit 0 1 2 5 15
echoXmlComment "DEBUG: ENTERING"
echoXmlComment "DEBUG: using $SCRIPTNAME script"
echoXmlComment "DEBUG: working base is $SCRIPTBASE"
echoXmlComment "DEBUG: path is $PATH"
echoXmlComment "DEBUG: $(date) : starting"

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

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

# get temporary filenames
XML_SETTINGS_FILE=settings.xml

echoXmlComment "DEBUG: INPUTFILE is $INPUTFILE"
cd $WORKING_DIRECTORY
echoXmlComment "DEBUG: entering working directory : $WORKING_DIRECTORY"

if ! cp $INPUTFILE $XML_SETTINGS_FILE &> /dev/null
then
    echoXmlErrorMessage "can't copy given file $INPUTFILE"
    echoXmlComment "DEBUG: EXITING"
    exit 1
fi

# Start real job

# check xml descriptor file
checkXmlDescriptorFile $XML_SETTINGS_FILE || exit $?
# generating yoga descriptor file
generateYogaDescFile $WORKING_DIRECTORY $XML_SETTINGS_FILE settings.i || exit $?
# decode base64 files if any
decodeB64Files $(ls *.b64)

# generating $BATCH_FILE into current directory
YOGARESULT_FILE=$PWD/yoga.xml
BATCH_FILE=runSettings.i
echo "/* Generated by $SCRIPTBASE/$SCRIPTNAME */" > $BATCH_FILE
echo "_GUI_SPECIALS_=1;" >> $BATCH_FILE
echo "#include \"$YOGA_LOCATION/LITpro/yorick/LITpro.i\"" >> $BATCH_FILE
cat >> $BATCH_FILE << EOF
world = lp_load_model("settings.i");
/*show_parameters(world);*/
lp_go_fit(world${INPUTARGS},quiet=1);
lpm_modelize_all_data(world);

summary="";
fit_info=summary+"\\nParameters: \\n"+lp_show_parameters(world)+lp_show_fit(world);
h_set,world,gui_info=fit_info;
filename="yoga.xml"
out=open(filename,"w");
res=oi_show_in_xml(world, out, "world");
write, "world stored into "+filename;


quit;
EOF

# Run batch
if ! RES="$(runYorickBatch "$BATCH_FILE")"
then
    echoXmlComment "$RES"
    extractError "$RES"
    exit 1
fi
echoXmlComment "$RES"
extractError "$RES"

if [ -e yoga.xml ]
then
    # prepare base64Encoded file that will be included by update xslt process
    encode64.py yoga.xml yoga.xml.b64
    echo "<resultFile  name=\"yoga.xml\" href=\"data:text/xml;base64,$(cat yoga.xml.b64)\">" > yogaResultFile.xml
    echo "<description>xml result file returned by yorick</description>" >> yogaResultFile.xml
    echo "</resultFile>" >> yogaResultFile.xml

    gzip -c $YOGARESULT_FILE > $YOGARESULT_FILE.gz
    encode64.py $YOGARESULT_FILE.gz $YOGARESULT_FILE.gz.b64
    echo -n "<result href='data:text/xml/x-gzip;base64,$(cat $YOGARESULT_FILE.gz.b64)'></result>" > $YOGARESULT_FILE.gz.b64.xml
fi
# update input file with xml generated file
XSLT_FILE=$SCRIPTBASE/xslt/updateSettingsWithYogaResult.xsl
OUTPUT_FILE=$PWD/updatedSettings.xml
XML_FILE=$XML_SETTINGS_FILE

if ! xsltproc --path .:$SCRIPTBASE/xslt:$PWD -o $OUTPUT_FILE --stringparam useYogaB64File "$useYogaB64File" --stringparam includeFileInResult "$includeFileInResult" --stringparam yogaB64File $YOGARESULT_FILE.gz.b64.xml --stringparam yogaFile $YOGARESULT_FILE $XSLT_FILE $XML_FILE
then
    echo "<message type=\"ERROR\">"
    echo "ERROR: can't generate '$OUTPUT_FILE'"
    echo "ERROR: reason is"
    xsltproc --path .:$SCRIPTBASE/xslt:$PWD $XSLT_FILE $XML_FILE 2>&1
    echo "</message>"
    exit 1
fi

echoXmlComment "DEBUG: '$XML_FILE' transformed into '$OUTPUT_FILE'"
echoXmlComment "DEBUG: '$OUTPUT_FILE' file content:"

cat $OUTPUT_FILE

#not needed actually
convertImg()
{
    #place something like following lines to generate and return one image
#window, display="",hcp="dummy.ps";
#lp_plot_radial, world, residuals=1
#pdf, "vis2_residuals";
    for img in vis2_residuals
do
    if convertPdfToPng ${img}.pdf
    then
        encode64.py ${img}.png ${img}.png.b64
        encode64.py ${img}.pdf ${img}.pdf.b64
        echo "<resultFile  name=\"${img}.png\" href=\"data:image/png;base64,$(cat ${img}.png.b64)\">"
        echo "<description>$img plot</description>"
        echo "</resultFile>"
        echo "<resultFile  name=\"${img}.pdf\" href=\"data:application/pdf;base64,$(cat ${img}.pdf.b64)\">"
        echo "<description>$img plot</description>"
        echo "</resultFile>"
    else
        echo "<message type=\"ERROR\">Can't get ${img} plot</message>"
    fi
done
echo
}

# HERE ENDS THE SCRIPT
echoXmlComment "DEBUG: EXITING"
echo "$(date) : $SCRIPTNAME stops" >> $SCRIPTBASE/log/yoga.log
exit 0
