#!/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/

CLASSPATH_VAR=
for FILE in $( ls ${distDir}/share/java/*.jar)
do
    if [ ! -z "$CLASSPATH_VAR" ]
    then
	CLASSPATH_VAR=$CLASSPATH_VAR:
    fi
    CLASSPATH_VAR=$CLASSPATH_VAR$FILE
done

bootstrapEnvVars=$(java -cp $CLASSPATH_VAR org.lsst.ccs.bootstrap.BootstrapEnvironmentUtils "ALL_IN_ONE" "$@" $defaultApp)
eval "$bootstrapEnvVars"

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 java $CCS_JAVA_OPTS $BOOTSTRAP_JAVA_OPTS -cp $CLASSPATH org.lsst.ccs.bootstrap.Bootstrap "$@" $defaultApp
fi
exit $EXIT_CODE
