#!/bin/bash
# use this script 
# - to test configuration 
# - to init other script sourcing general settings

# Next variables permit to get ys home (SCRIPTBASE)
SCRIPTSTARTUPDIR=$PWD
SCRIPTNAME=$(basename $0)
# if this file is sourced it does return the caller program name
SCRIPTBASE=$(dirname $0)/..
#make SCRIPTBASE fully qualified
SCRIPTBASE=$( cd $SCRIPTBASE && pwd )


# BEGIN USER ADJUSTABLE PART

# uncomment next line if you want to change default yoga location (ys/yoga)
#USER_YOGA=/home/user/yoga
# next yorick revision works with model fitting 
#USER_YORICK_HOME=$SCRIPTBASE/yorick/yorick-2.1.02c-linux-i686/
# next yorick revision works with model fitting is newer and is used by cral
# users
USER_YORICK_HOME=$SCRIPTBASE/yorick/yorick-2.1.04x-2007-04-17-linux-ix86/
#USER_YORICK_HOME=/home/mella/INTROOT/yorick/
# yorick/runSettings.i contains the yoga path that should be adjusted
# it's default value is ../yoga/...

# END USER ADJUSTABLE PART


# HERE BEGINS THE SCRIPT

# define one scientific locale
export LC_ALL=C
# do output xml by default
export NO_XML=""


# define some functions

# define zoom factor and rigth resolution applied for pdf-> png conversions
convertPdfToPng()
{
 pdfFile="$1"
 pngFile="$(basename "${pdfFile}" .pdf)".png
 convert -density 200 $pdfFile -resize 50% -depth 8 $pngFile
}


checkCommand(){
    prog=$1

    if which $prog &> /dev/null
    then
        echo "    [OK] Command '$prog' found '$(which $prog)'"
        return 0
    else
        echo "    [KO] Command '$prog' not found"
        return 1
    fi
}

# This function create a tmp working directory and cd into.
# WORKING_DIRECTORY env var is created
enterTmpWorkingDir(){
    # creating one working area
    if ! WORKING_DIRECTORY=$(mktemp -d)
    then
        echoXmlErrorMessage "Can't create working directory"
        echoXmlComment "DEBUG: EXITING"
        exit 1
    fi
    echoXmlComment "DEBUG: entering working directory : $WORKING_DIRECTORY"
    cd $WORKING_DIRECTORY
    export WORKING_DIRECTORY
}


# use trap beforeExit 0 1 2 5 15 
# to clean up the tmp working directory unless DONOTREMOVETMP has one non empty
# value
# one closing return element is return unless NO_XML has one non empty value
beforeExit()
{

    echoXmlComment "DEBUG: EXITING"
    echo "$(date) : STOP $SCRIPTNAME " >> $SCRIPTBASE/log/yoga.log
    if [ -z "$NO_XML" ]
    then
        echo '</response>'
    fi
    if [ -d "$WORKING_DIRECTORY" -a -z "$DONOTREMOVETMP" ]
    then
        rm -rf "$WORKING_DIRECTORY" 
        echo
    fi
}

echoXmlComment()
{
    if [ -z "$NO_XML" ]
    then
        echo -n "<!-- "
        echo -n "$*" |tr -s "-"
        echo "-->"
    fi
}

echoXmlMessage()
{
    type="$1"
    shift 1
    content="$*"
    echo -ne "<message type=\"$type\"><![CDATA["
    echo "$content]]>"
    echo "</message>"
}

echoXmlErrorMessage()
{
    type="ERROR"
    content="$*"
    echoXmlMessage $type "$content"
}

echoXmlWarningMessage()
{
    type="WARNING"
    content="$*"
    echoXmlMessage $type "$content"
}


echoPre()
{
    echo -e "<pre>$*</pre>"
}

extractError()
{
    inputStr="$*"
    echo "$inputStr" | awk '{if ($1=="</message>"){end=1;start=0;print} if($1=="<message"){start=1; end=0};if(start==1&&end!=1)print;}'
}

runYorickBatch()
{
    BATCH_FILE=$1

    if [ ! "$#" -eq 1 ]
    then
      echoXmlErrorMessage "missing batch file"
      return 1 
    fi

    echo
    echoXmlComment "DEBUG: '$BATCH_FILE' batch content:"
    echoXmlComment "$(nl $BATCH_FILE)"
    echo

    # start yorick loop
    echoXmlComment "DEBUG: starting yorick"
    errorFile=tmp_$$.err
    if ! RES="$(yorick -batch $BATCH_FILE 2> $errorFile)"
    then 
        echoXmlComment "DEBUG: yorick terminated in error"
        if [ -s "$errorFile" ]
        then
            echoXmlErrorMessage "$(cat $errorFile)"
            rm $errorFile
        fi
        echoXmlComment "$RES"
        extractError "$RES"
        exit 1
    fi
    echoXmlComment "$RES"
    extractError "$RES"
}

decodeB64Files()
{
# searching for files
FILES=($*)
if test ${#FILES[@]} -ge 1
then
    echoXmlComment "DEBUG: decoding ${#FILES[@]} joined base64 file(s)"
    for f in "${FILES[@]}"
    do
        final=${f%%.b64}
        decode64.py $f ${final}.gz
        gzip -c --force -d ${final}.gz > $final 2>/dev/null
	rm ${final}.gz &> /dev/null
        echoXmlComment "DEBUG: file '$final' decoded "
        echoXmlComment "DEBUG: md5sum is $(md5sum $final)"
    done
else
    echoXmlComment "DEBUG: no joined file "
fi    
echoXmlComment "DEBUG: actual list of files is '$(ls -C)'"
}

copyXmlInputFile(){
# Store full path of INPUTFILE if given path was not absolute
    INPUTFILE="$1"
    OUTPUTFILE="$2"
    if test "${INPUTFILE:0:1}" != "/" 
    then
        INPUTFILE="$SCRIPTSTARTUPDIR/$1"
    fi

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

}

checkXmlDescriptorFile()
{
    SETTINGS_FILE=$1
# check well formed input file
if ! xmllint --noout $SETTINGS_FILE &> /dev/null
then
    echoXmlWarningMessage "given file is not well formed, reason is:\n$(xmllint --noout $SETTINGS_FILE 2>&1)"
    return 1
fi
echoXmlComment "DEBUG: file input format is well formed"

# check valid input file
if ! xmllint --noout --schema $SCRIPTBASE/xsd/LITproSettings.xsd  $SETTINGS_FILE &> /dev/null
then
    echoXmlWarningMessage "given file is not valid, reason is:\n$(xmllint --noout --schema $SCRIPTBASE/xsd/LITproSettings.xsd  $SETTINGS_FILE 2>&1)"
    return 1
fi
echoXmlComment "DEBUG: file input format is valid"
}

generateYogaDescFile()
{
    WORKING_DIRECTORY=$1
    XML_SETTINGS_FILE=$2
    YOGA_DESC=$3
    if ! xsltproc -o $YOGA_DESC --stringparam workingDirectory "&quot;${WORKING_DIRECTORY}/&quot;" $SCRIPTBASE/xslt/settingsToLITproDesc.xsl $XML_SETTINGS_FILE
then
    echoXmlErrorMessage "can't generate $PWD/$YOGA_DESC, reason is:\n$(xsltproc  --stringparam workingDirectory "&quot;${WORKING_DIRECTORY}/&quot;" $SCRIPTBASE/xslt/settingsToLITproDesc.xsl $XML_SETTINGS_FILE 2>&1)"
    return 1
fi
echoXmlComment "DEBUG: file input transformed into $YOGA_DESC"
echoXmlComment "DEBUG: settings content:"
echoXmlComment "$(nl $YOGA_DESC)"
}
# BEGIN VARIABLE EXPORTS

# set YOGA_LOCATION
if test -z $USER_YOGA
then
    export YOGA_LOCATION=$SCRIPTBASE/yoga
else
    export YOGA_LOCATION=$USER_YOGA
fi

# set YORICK_HOME
if test -n "$USER_YORICK_HOME"
then
        export PATH=$USER_YORICK_HOME/bin/:$PATH
fi
        
# set this bin into path
export PATH=$SCRIPTBASE/bin:$PATH

# END VARIABLE EXPORTS


if test "$SCRIPTNAME" = "env.sh"
then
    # check can be done here to tell more on user configuration
    echo "Env informations:"
    echo "    SCRIPTBASE is '$SCRIPTBASE'"
    echo "    SCRIPTNAME is '$SCRIPTNAME'"

    #  yorick section
    if test -n "$USER_YORICK_HOME"
    then
        echo "    User has defined a new yorick path '$USER_YORICK_HOME'"
    else
        echo "    User has not defined a new yorick path"
    fi
    echo "    ( use 'USER_YORICK_HOME' into env.sh file if you need to adjust it )"
 
    echo 

    #  command section
    echo "Checking required commands:"
    for cmd in yorick xsltproc xmllint 
    do
        checkCommand $cmd
    done
    
    echo 
    
    # tmp permission section
    echo "Checking file permission for $SCRIPTBASE/tmp "
    echo "    ( all permission must be -wx at least if this setup can be used \
behind one webserver )"
    echo -n "    "
    ls -ld $SCRIPTBASE/tmp
 
    # log permission section
    echo "Checking file permission for $SCRIPTBASE/log/yoga.log "
    echo "    ( all permission must be -wx at least to allow traces of webserver )"
    echo -n "    "
    ls -ld $SCRIPTBASE/log/yoga.log
    
    echo 
   
    echo "Checking LITpro.i from yoga location:"
    if test -d $YOGA_LOCATION
    then
        LITproFile="$YOGA_LOCATION/LITpro/yorick/LITpro.i"
        if test -e "$LITproFile"
        then
            echo "    [OK] YOGA_LOCATION seems ok into '$YOGA_LOCATION'"
        else
            echo "    [KO] YOGA_LOCATION must be adjusted '$YOGA_LOCATION'"
            echo "         missing file: '$LITproFile'"
        fi
    else
        echo "    [KO] YOGA_LOCATION must be adjusted '$YOGA_LOCATION'"
    fi

else
    # Just do a simple log to get traces
    echo "$(date) : START $SCRIPTNAME $*" >> $SCRIPTBASE/log/yoga.log
    echoXmlComment "DEBUG: $(date) : starting $SCRIPTNAME, working base is $SCRIPTBASE"
    echoXmlComment "$SCRIPTBASE/log/yoga.log"
fi
