#! /bin/bash
VERBOSE=0
linkName=`basename $0 | awk -F. '{print $1}'`
#Implementation as suggested in LSSTCCS-130
osType=`uname`
if [ "$osType" == "Linux" ]
then 
    scriptFullPath=`readlink -fn $0` 
else 
    scriptFullPath=`perl -e "use Cwd 'abs_path'; print abs_path('$0')"`
fi 

bootstrapName=`basename ${scriptFullPath} | awk -F. '{print $1}'`

if [ $linkName != $bootstrapName ]
then
    defaultApp="--app "$linkName
fi

# To find the full path of the script CD into the dir containing the script
binDir=$(cd "$(dirname "$scriptFullPath")"; pwd -P)

distDir=`dirname $binDir`

export CCS_DISTRIBUTION_HOME=$distDir

export CCS_RESOURCE_PATH=$CCS_RESOURCE_PATH:$distDir/../etc/:~/ccs/etc/:/etc/ccs/

mainJar=$distDir/share/java/org-lsst-ccs-bootstrap-2.2.18.jar

export LD_LIBRARY_PATH=`java -cp $mainJar org.lsst.ccs.bootstrap.BootstrapEnvironmentUtils "LD_LIBRARY_PATH" "$@" $defaultApp`

BOOTSTRAP_JAVA_OPTS=`java -cp $mainJar org.lsst.ccs.bootstrap.BootstrapEnvironmentUtils "JAVA_OPTS" "$@" $defaultApp`

CLASSPATH=`java -cp $mainJar org.lsst.ccs.bootstrap.BootstrapEnvironmentUtils "CLASSPATH" "$@" $defaultApp`

java $CCS_JAVA_OPTS $BOOTSTRAP_JAVA_OPTS -cp $CLASSPATH org.lsst.ccs.bootstrap.Bootstrap "$@" $defaultApp
EXIT_CODE=$?
if [ $EXIT_CODE != 0 ] && [ $EXIT_CODE != 130 ] && [ $VERBOSE != 0 ]
then
    echo "EXECUTION FAILED (RC=${EXIT_CODE}):"
    echo exec java $CCS_JAVA_OPTS $BOOTSTRAP_JAVA_OPTS -cp $CLASSPATH org.lsst.ccs.bootstrap.Bootstrap "$@" $defaultApp
fi
exit $EXIT_CODE

