#!/bin/bash


# HERE BEGINS THE SCRIPT
# all output are nested under one result element
# this is actually a HACK because (schema) castor binding enable any content under 
# result element 
SCRIPTSTARTUPDIR=$PWD
SCRIPTNAME=$(basename $0)
SCRIPTBASE=$(dirname $0)/..
#make SCRIPTBASE fully qualified
SCRIPTBASE=$( cd $SCRIPTBASE && pwd )

source $SCRIPTBASE/bin/env.sh
enterTmpWorkingDir
trap beforeExit 0 1 2 5 15
echo "<response>"

# Start real job

BATCH_FILE=getModel.i
XML_MODELS=yogaModels.xml
# generating BATCH_FILE into current directory
echo "/* Generated by $SCRIPTBASE/$SCRIPTNAME */" > $BATCH_FILE
echo "_GUI_SPECIALS_=1;" >> $BATCH_FILE
echo "#include \"$YOGA_LOCATION/LITpro/yorick/LITpro.i\"" >> $BATCH_FILE
echo "filename=\"$XML_MODELS\"" >> $BATCH_FILE
cat >> $BATCH_FILE << EOF

models=lpb_functions();
out=open(filename,"w");
res=oi_show_in_xml(models, out, "models");
write, "models stored into "+filename;
quit;
EOF

echoXmlComment "DEBUG: $BATCH_FILE content:"
echoXmlComment "\n$(nl $BATCH_FILE)\n"

# start yorick loop
echoXmlComment "DEBUG: starting yorick"
if ! ret=$(yorick -batch $BATCH_FILE 2>&1)
then 
    echoXmlErrorMessage "yorick batch encountered errors"
    echoPre "$ret"
    echoXmlComment "DEBUG: EXITING"
    exit 1
fi
#ret can't be outputed because -- are returned  :((
echoXmlComment "DEBUG: yorick terminated"

# generating updated result file
OUTPUT_FILE=$PWD/settingsModels.xml
XSLT_FILE=$SCRIPTBASE/xslt/yogaModelsToSettingsModels.xsl
XML_FILE=$XML_MODELS
if ! xsltproc -o $OUTPUT_FILE  $XSLT_FILE $XML_FILE
then
    echoXmlErrorMessage "can't generate '$OUTPUT_FILE'"
    echoXmlErrorMessage "reason is"
    echoXmlComment $(xsltproc  $XSLT_FILE $XML_FILE 2>&1)
    echoXmlComment "DEBUG: EXITING"
    exit 1
fi

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

cat $OUTPUT_FILE

# HERE ENDS THE SCRIPT
exit 0
