#! /bin/bash

# This script starts the extract-table example program
# from the PDS4 tools library examples.
#
# Run "extract-table -h" to see usage information.
#
# These environment variables alter how the program is
# run:
#
# PDS4_TOOLS_HOME - If set, classpath will include
#   all JAR files in $PDS4_TOOLS_HOME/lib/. Otherwise
#   defaults to the parent directory of this script.
#
# PDS4_TOOLS_OPTS - This may contain additional JVM
#   arguments and options.
#
# PDS4_TOOLS_ARGS - This may contain additional arguments
#   to pass to the application.
#
# JAVACMD - If set, this is the command that runs the
#   Java JRE. Defaults to the usual Java command for the
#   JRE installed at $JAVA_HOME.
#
# JAVA_HOME - If set, this is the location where the Java
#   JRE can be found. If not set, Java is assumed to be
#   in the classpath.
#
# CLASSPATH - If set, this will be appended to the end of
#   the classpath obtained by adding all JARs in the lib/
#   directory.
#
# exec_debug - If set to a true value, does not run the
#   application. Instead, just echoes the Java command that
#   would have been executed.

PROGDIR=`dirname "$0"`
PROGNAME=`basename "$0"`

if [ -z "$PDS4_TOOLS_HOME" ]; then
  PDS4_TOOLS_HOME=`(cd $PROGDIR; cd ..; pwd)`
fi

LIB="$PDS4_TOOLS_HOME/lib"

LOCAL_CLASSPATH=$(find "$LIB" -name '*.jar' -exec echo -n "{}:" \; | sed 's/:$//')

# This logic is the same as in the Apache Ant start script.
if [ -z "$JAVACMD" ] ; then
  if [ -n "$JAVA_HOME"  ] ; then
    # Check nonstandard AIX Java locations, first.
    if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
      JAVACMD="$JAVA_HOME/jre/sh/java"
    elif [ -x "$JAVA_HOME/jre/bin/java" ] ; then
      JAVACMD="$JAVA_HOME/jre/bin/java"
    else
      JAVACMD="$JAVA_HOME/bin/java"
    fi
  else
    JAVACMD=`which java 2> /dev/null `
    if [ -z "$JAVACMD" ] ; then
        JAVACMD=java
    fi
  fi
fi

if [ ! -x "$JAVACMD" ] ; then
  echo "Error: JAVA_HOME is not defined correctly."
  echo "  We cannot execute $JAVACMD"
  exit 1
fi

MAIN_CLASS=gov.nasa.pds.objectAccess.example.ExtractTable

exec_command="exec \"$JAVACMD\" $PDS4_TOOLS_OPTS -cp \"$LOCAL_CLASSPATH\" -Dpds4.tools.home=\"$PDS4_TOOLS_HOME\" -Dpds4.tools.progname=\"$PROGNAME\" $MAIN_CLASS"
if [ -n "$exec_debug" ]; then
  echo "$exec_command" "$@" $PDS4_TOOLS_ARGS
else
  eval "$exec_command" "$@" $PDS4_TOOLS_ARGS
fi
