#!/bin/bash


# HERE BEGINS THE SCRIPT

SCRIPTSTARTUPDIR=$PWD
SCRIPTNAME=$(basename $0)
SCRIPTBASE=$(dirname $0)/..
#make SCRIPTBASE fully qualified
SCRIPTBASE=$( cd $SCRIPTBASE && pwd )


usage()
{
    echoPre "\nUsage:\n $(basename $0) xmlDescriptorFile.xml [groupId]\n"   
}

source $SCRIPTBASE/bin/env.sh
enterTmpWorkingDir
XML_SETTINGS_FILE=settings.xml
copyXmlInputFile $1 ${XML_SETTINGS_FILE}
trap beforeExit 0 1 2 5 15
echo "<response>"

# check cmd line
if test $# -lt 1
then
    echoPre "Missing file as argument"
    usage 
    exit 1
fi

if [ -n "$2" ]
then
    GROUP=",groups=$2"
else 
    GROUP=""
fi

# Start real job:

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

# generating batch into current directory
BATCH_FILE=batch.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");
window, display="",hcp="img.ps";
lp_plot_uvcoverage, world $GROUP;
pltitle_height = 12;
pltitle, "uv coverage";
pdf, "img";
quit;
EOF

# Run batch
runYorickBatch "$BATCH_FILE"

convertPdfToPng img.pdf
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 "  <resultFile name=\"img.pdf\" href=\"data:application/pdf;base64,$(cat img.pdf.b64)\"/>"

# HERE ENDS THE SCRIPT
