#!/bin/sh

#+
#  Name:
#     topcat

#  Purpose:
#     Invokes the TOPCAT application on unix

#  Description:
#     This shell script invokes the TOPCAT application.

#  Notes:
#     This script locates a JVM and invokes it using the relevant class in 
#     the tables jar file.  It currently does not do this using 'java -jar'
#     as this would prevent any user additions to the classpath without
#     additional machinery in both this script and the application
#     classloading; these are required for use of JDBC.  May revise
#     this at some stage.

#  Authors:
#     MBT: Mark Taylor (Starlink)
#-

#  Find where this script is located.  We normally find this out by
#  looking at where we were invoked from, but this can be overridden
#  by setting TOPCAT_DIR (necessary if invocation is from another
#  directory because of filesystem links).
if test -z "$TOPCAT_DIR"
then
    bindir="`dirname $0`"
else
    bindir="$TOPCAT_DIR"
fi

#  Locate the application jar file.  This is relative to this script.

appjar="$bindir/../lib/topcat/topcat.jar"
if test ! -f "$appjar"; then
   echo "Failed to locate $appjar."
   exit 1
fi

#  Locate the java startup script.

starjava="$bindir/starjava"
if test ! -f "$starjava"; then
   echo "Failed to locate '$bindir/starjava'."
   exit 1
fi

#  Divide the arguments into two parts: those destined as flags for
#  the java binary, and the rest.
javaArgs=""
appArgs=""
while test "$1"
do
   if echo $1 | grep -- '^-[XD]' >/dev/null; then
      javaArgs="$javaArgs \"$1\""
   elif [ "$1" = "-classpath" -a -n "$2" ]; then
      shift
      export CLASSPATH="$1"
   else
      appArgs="$appArgs \"$1\""
   fi
   shift
done

#  Check for Cygwin and transform paths.
case "`uname`" in
  CYGWIN*) 
    if test -n "$CLASSPATH"; then
       CLASSPATH=`cygpath --path --windows "${appjar}:$CLASSPATH"`
    else
       CLASSPATH=`cygpath --windows "${appjar}"`
    fi
  ;;
  *)
    CLASSPATH="${appjar}:${CLASSPATH}"
  ;;
esac


#  Run topcat

cmd="$starjava \
        $javaArgs \
        -enableassertions \
        -Duk.ac.starlink.topcat.cmdname=topcat \
        -classpath \${CLASSPATH} uk.ac.starlink.topcat.Driver \
        $appArgs"
eval "$cmd"

