#!/bin/sh

# Perform checking of env-vars and create the temp-directory
check_settings()
{
  # Find the directory in which this script is located
  SCRIPT_DIR=`dirname $0`
  if [ "$SCRIPT_DIR" = "." ]
  then
    SCRIPT_DIR=`pwd`
  fi

  # Now calculate the HOME-dir of the visualizers
  VIS_HOME=`dirname $SCRIPT_DIR`

  # Prepare the Visualizer DIR in the users HOME-directory
  if [ ! -d ~/.imvisualizer ]
  then
    mkdir ~/.imvisualizer
  fi

  # Prepare the log file
  LOGFILE=~/.imvisualizer/imvisualizer.log
  if [ -f $LOGFILE ]
  then
    rm -f $LOGFILE
    test_warning "Could not access the old log-file. Logging may not work correctly."
  else
    touch $LOGFILE
    test_warning "Could not create the log-file. Logging may not work correctly."
  fi

  # Write the current timestamp into the LOGFILE
  date >>$LOGFILE

  # Check for the configuration file
  CONFIG_FILE=$SCRIPT_DIR/imvisualizer.cfg
  USER_CONFIG_FILE=~/.imvisualizer/imvisualizer.cfg
  test -f $CONFIG_FILE
  test_warning "Configuration file $CONFIG_FILE could not be opened. No defaults will be used."
}

# Extracts the command line parameters. If the parameters are wrong or incomplete, a help text is displayed.
extract_parms()
{
  # First get defaults from the config file.
  if [ -f $CONFIG_FILE ]
  then
    PARAMS_SYS=`cat $CONFIG_FILE`
  fi

  # Now get settings from the user config file.
  if [ -f $USER_CONFIG_FILE ]
  then
    PARAMS_USER=`cat $USER_CONFIG_FILE`
  fi

  get_params $PARAMS_SYS $PARAMS_USER "$@"
#  get_params $PARAMS_SYS $PARAMS_USER ${1+"$@"}
}

get_params()
{
  # Now get the values from command line input
  while test $# -gt 0
  do
    case $1 in
      -javahome) shift;JAVA_HOME=$1;;
      -J)        shift;JAVA_OPT=$1;;
      -cp:p)     shift;CP_P=$1;;
      -cp:a)     shift;CP_A=$1;;
      -h|-help|--help|-?) help_me;exit 1;;
      -dbname)          add_params $1 $2;shift;;
      -dbhostname)      add_params $1 $2;shift;;
      -dbportnumber)    add_params $1 $2;shift;;
      -dbdatacol)       add_params $1 $2;shift;;
      -dbdriver)        add_params $1 $2;shift;;
      -dbpassword)      add_params $1 $2;shift;;
      -dbprimarykeycol) add_params $1 $2;shift;;
      -dbprofile)       add_params $1 $2;shift;;
      -dbpropcol)       add_params $1 $2;shift;;
      -dbtablename)     add_params $1 $2;shift;;
      -dburl)           add_params $1 $2;shift;;
      -dbuserid)        add_params $1 $2;shift;;
      -fullversion)     add_param $1;;
      -locale)          add_params $1 $2;shift;;
      -reset)           add_param $1;;
      -version)         add_param $1;;
      *)         if [ "$ARGUMENT" = "" ]
                 then
                   ARGUMENT="$1";
                 fi
    esac
    shift
  done
}


# add a parameter with its argument
add_params()
{
  if [ $# -ne 2 ]
  then
    echo $1 needs an argument;
    exit 1;
  fi
  
  if [ "$CMD_LINE" = "" ]
  then
    CMD_LINE="$1 $2"
  else
    CMD_LINE="$CMD_LINE $1 $2"
  fi
}

# add a single parameter
add_param()
{
  if [ "$CMD_LINE" = "" ]
  then
    CMD_LINE="$1"
  else
    CMD_LINE="$CMD_LINE $1"
  fi
}


# Checks, if the Java VM is at the specified location
check_vm()
{
  # First try to find the java at the specified location
  JAVA_VM=$JAVA_HOME/bin/java
  if [ ! -f $JAVA_HOME/bin/java ]
  then
    echo "The Java Runtime $JAVA_VM was not found in your specified javahome. Trying to get a Java VM from your PATH." | tee -a $LOGFILE
    # try to get the java vm from the path
    JAVA_VM=`which java 2>/dev/null`
    test_failed "Could not find a Java VM in your PATH, too."
  fi
}

# Call the Main Class from the Visualizers
start_visualizers()
{
  # is there a CLASSPATH already set?
  if [ "$CLASSPATH" != "" ]
  then
    CP=$CLASSPATH:
  else
    CP=""
  fi

  # add the pathes from command line to the classpath
  if [ "$CP_P" != "" ]
  then
    CP=$CP_P:$CLASSPATH
  fi

  # Check for all jar and zip files in the $VIS_HOME/lib directory and add them to a list
  visClassPath=`ls -1 $VIS_HOME/lib/*.jar 2>/dev/null`:`ls -1 $VIS_HOME/lib/*.zip 2>/dev/null`
  # replace the spaces with :'s
  visClassPath=`echo $visClassPath|sed -e "s/ /:/g"`

  CP=$CP$visClassPath:$VIS_HOME/lib
  if [ "$CP_A" != "" ]
  then
    CP=$CP:$CP_A
  fi

  # Start the Java VM with the main visualizer class, enable the logging, if available.
  if [ "$ARGUMENT" != "" ]
  then
    $JAVA_VM -cp $CP $JAVA_OPT com.ibm.iminer.visualizer.IDMVisualizerStarter $CMD_LINE "$ARGUMENT" 2>&1 | tee -a $LOGFILE
  else
    $JAVA_VM -cp $CP $JAVA_OPT com.ibm.iminer.visualizer.IDMVisualizerStarter $CMD_LINE 2>&1 | tee -a $LOGFILE
  fi

  RC=$?
  # if the return code is 1, display the usage message
  if [ "$RC" = "1" ]
  then
    help_me
  fi
}

# Displays the help
help_me()
{
  echo "Startup of Intelligent Miner for Data Visualization"
  echo
  echo "Command syntax: "`basename $0`" [<options>] [-J <jvm-options>] [<resultfile>]"
  echo
  echo "You can use the following options:"
  echo "   -cp:a <classpath>"
  echo "        To append <classpath> to the classpath of the visualizer"
  echo "   -cp:p <classpath>"
  echo "        To prepend <classpath> to the classpath of the visualizer"
  echo "   -dbname <dbname>"
  echo "        To define the database name, if model in database"
  echo "   -dbhostname <dbhostname>"
  echo "        To define the host name of database, if model in database"
  echo "   -dbportnumber <dbportnumber>"
  echo "        To define the port number of database, if model in database"
  echo "   -dbdatacol <dbdatacol>"
  echo "        To define the model column name, if model in database"
  echo "   -dbdriver <dbdriver>"
  echo "        To define the JDBC driver, if model in database"
  echo "   -dbpassword <dbpasssword>"
  echo "        To define the database password, if model in database"
  echo "   -dbprimarykeycol <dbprimarykeycol>"
  echo "        To define the primary key column name, if model in database"
  echo "   -dbprofile <dbprofile>"
  echo "        To define the profile name, if model in database"
  echo "   -dbpropcol <dbpropcol>"
  echo "        To define the properties column name, if model in database"
  echo "   -dbtablename <dbtablename>"
  echo "        To define the table name, if model in database"
  echo "   -dburl <dburl>"
  echo "        To define the URL, if model in database"
  echo "   -dbuserid <dbuserid>"
  echo "        To define the database userid, if model in database"
  echo "   -fullversion"
  echo "        To display full version information of the product"
  echo "   -h -help --help -?"
  echo "        To display help information"
  echo "   -javahome <home-dir of your java runtime environment>"
  echo "        To specify the JDK directory"
  echo "   -J <jvm_option>"
  echo "        To pass <jvm_option> to JVM (type \"-J -help\" for a list of jvm options)"
  echo "   -locale <locale>"
  echo "        To force the visualizer to use the specified locale."
  echo "   -reset"
  echo "        To reset the user settings"
  echo "   -version"
  echo "        To display version information of the product\n\n\nSee the visualizer documentation for details."
  echo
  echo "   <resultfile> display this data mining result"
  echo
  echo "You can put defaults for the command line into the file imvisualizer.cfg."
  echo "System-wide defaults are located in the bin-directory of the visualizers."
  echo "User specific defaults are located in the home-directory of an user in ~/.imvisualizer/"
  echo
}

## Helper functions

# Tests the Return-Code of a command. If it is not 0 the script will abort with a supplied error message
test_failed()
{
  RC=$?
  if [ "$RC" != "0" ]
  then
    echo "Error: $*" | tee -a $LOGFILE
    echo "Abort." | tee -a $LOGFILE
    exit $RC
  fi
}

# Tests the Return-Code of a command. If it is not 0 the script will write out a supplied error message
test_warning()
{
  if [ "$?" != "0" ]
  then
    echo "Warning: $*" | tee -a $LOGFILE
  fi
}

# Main routine

check_settings
extract_parms "$@"
check_vm
start_visualizers

exit 0
