#!/bin/sh

# TODO: add support for relative paths in link source

OW_TOOL_CLASS=com.baan.owtools.fw.icvt.Start
OW_COMMAND="$0 $*"
OW_OLD_CLASSPATH=$CLASSPATH

if [ "$OW_SCRIPT_DEBUG" = "" ] ; then
  OW_SCRIPT_DEBUG=off
fi

case $OW_SCRIPT_DEBUG in
  on) ;;
  off) ;;
  *) echo \*\*\* ERROR \*\*\*
     echo OW_SCRIPT_DEBUG may only have values \'on\' or \'off\'
     exit 1 ;;
esac

## resolve links - $0 may be a link
prog=$0
progname=`basename $0`

while [ -h "$prog" ] ; do
  ls=`ls -ld "$prog"`
  link=`expr "$ls" : '.*-> \(.*\)$'`
  if expr "$link" : '.*/.*' > /dev/null; then
    prog="$link"
  else
    prog="`dirname $prog`/$link"
  fi
done
  
OW_SCRIPTDIR=`dirname "$prog"`

jarFile=$OW_SCRIPTDIR/owicvt.jar
if [ -f "$jarFile" ] ; then
  CLASSPATH=$jarFile
else
  echo \*\*\* ERROR \*\*\*
  echo owicvt.jar not found in directory \'$OW_SCRIPTDIR\'
  exit 1
fi

if [ -z "$OW_JI" ] ; then
  if [ -n "$JAVA_HOME" ] ; then
    javaHomeJi=$JAVA_HOME/bin/java
    if [ -f $javaHomeJi ] && [ -x $javaHomeJi ] ; then
      OW_JI=$javaHomeJi
    else
      echo \*\*\* ERROR \*\*\*
      echo JAVA_HOME, if set, must point to the java installation directory.
      echo i.e. \$JAVA_HOME/bin/java must exist and be executable.
      exit 1
    fi
  fi
  if [ -n "$OW_JAVA_HOME" ] ; then
    owJavaHomeJi=$OW_JAVA_HOME/bin/java
    if [ -f $owJavaHomeJi ] && [ -x $owJavaHomeJi ] ; then
      OW_JI=$owJavaHomeJi
    else
      echo \*\*\* ERROR \*\*\*
      echo OW_JAVA_HOME, if set, must point to the java installation directory.
      echo i.e. \$OW_JAVA_HOME/bin/java must exist and be executable.
      exit 1
    fi
  fi
  if [ -z "$OW_JI" ] ; then
    OW_JI=`which java`
    if [ ! -f $OW_JI ] || [ ! -x $OW_JI ] ; then
      echo \*\*\* ERROR \*\*\*
      echo A Java VM could not be found.
      echo Install one and add it to your path or set one of the environment variables
      echo \(OW_JI, OW_JAVA_HOME or JAVA_HOME\) appropriately before rerunning this script.
      exit 1
    fi
  fi
elif [ ! -f $OW_JI ] || [ ! -x $OW_JI ] ; then
  echo \*\*\* ERROR \*\*\*
  echo OW_JI must be an executable file. \(OW_JI=$OW_JI\)
  exit 1
fi

if [ "$OW_SCRIPT_DEBUG" = "on" ] ; then
  OW_ICVT_JFLAGS="$OW_ICVT_JFLAGS -Dcom.baan.owimpl.fw.icvt.debug=true"
fi

OW_JAVA_COMMAND="$OW_JI $OW_ICVT_JFLAGS $OW_TOOL_CLASS $@"

export CLASSPATH
export OW_OLD_CLASSPATH
export OW_SCRIPTDIR
export OW_COMMAND
export OW_JI
export OW_JAVA_COMMAND

if [ "$OW_SCRIPT_DEBUG" = "on" ] ; then
  env
  echo
  echo Running command:
  echo $OW_JAVA_COMMAND
  echo
fi

$OW_JAVA_COMMAND
