#!/bin/sh
DB_VERSION=1
# -------------------------------------------------------------------
# queryJavaHome
# -------------------------------------------------------------------
queryJavaHome()
{
   while :
   do
      dummy=$JAVA_HOME
      $INFOTEXT -n "Please enter the path to your java 1.4 installation [$dummy] >> "
      dummy=`Enter $dummy`
      if [ -x "$dummy/bin/java" ]; then
         JAVA_VERSION=`$dummy/bin/java -version 2>&1 | grep "java version"`
         echo $JAVA_VERSION | grep "1.4" > /dev/null
         if [ $? -ne 0 ]; then
            $INFOTEXT "Invalid java version ($JAVA_VERSION), we need 1.4.x"
         else
            JAVA_HOME=$dummy
            break
         fi
      else
         $INFOTEXT "Can not execute $dummy/bin/java"
      fi   
   done
}

#
#  Parameters
#     $1   default database username
#     $2   directory with jars files
#
setupDB()
{
   DB_USER=$1
   DB_LIB_DIR=$2
   $INFOTEXT -u "\nSetup your database connection parameters"
   $INFOTEXT " "

   for i in  $DB_LIB_DIR/*.jar; do
      CP=$CP:$i
   done
   
   while : 
   do
     $INFOTEXT -ask p o -def p -n \
               "\nEnter your database type ( o = Oracle, p = PostgreSQL ) [p] >> "
     if [ $? -eq 0 ]; then
         queryPostgres
     else 
         queryOracle
     fi

     searchJDBCDriverJar $DB_DRIVER $DB_LIB_DIR

     testDB
     if [ $? -eq 0 ]; then
        break
     else
        $INFOTEXT -ask y n -def y \
                  -n "Do you want to repeat database connection setup? (y/n) [y] >>" 
        if [ $? -ne 0 ]; then
           break
        fi
     fi
   done   
}

queryDB() {
   
   DB_TYPE=$1
   DEFAULT_PORT=$2

   dummy=$DB_HOST
   $INFOTEXT -n "\nPlease enter the name of your $DB_TYPE db host [$dummy] >> "
   DB_HOST=`Enter $dummy`

   if [ "$DB_PORT" = "" ]; then
      dummy=$DEFAULT_PORT
   else
      dummy=$DB_PORT
   fi
   $INFOTEXT -n "\nPlease enter the port of your $DB_TYPE db [$dummy] >> "
   DB_PORT=`Enter $dummy`

   if [ "$DB_NAME" = "" ]; then
      dummy=arco
   else
      dummy=$DB_NAME
   fi
   $INFOTEXT -n "\nPlease enter the name of your $DB_TYPE database [$dummy] >> "
   DB_NAME=`Enter $dummy`

   if [ "$DB_USER" = "" ]; then
      dummy=arco_read
   else
      dummy=$DB_USER
   fi
   $INFOTEXT -n "\nPlease enter the name of the database user [$dummy] >> "
   DB_USER=`Enter $dummy`

   STTY_ORGMODE=`stty -g`
   while :
   do
      $INFOTEXT -n "\nPlease enter the password of the database user >> "
      stty -echo
      read DB_PW
      stty "$STTY_ORGMODE"
      $INFOTEXT -n "\n"
      $INFOTEXT -n "Please retype the password >> "
      stty -echo
      read DB_PW1
      stty "$STTY_ORGMODE"
      $INFOTEXT -n "\n"
      if [ "$DB_PW" = "$DB_PW1" ]; then
         break;
      else
        $INFOTEXT "password do not match"
      fi
   done
   
   queryDBSchema
   
}
#
#  Query the database schema
#  Uses DB_DRIVER, DB_USER
#  set the variables DB_SCHEMA
#
queryDBSchema() {
   case "$DB_DRIVER" in
     "org.postgresql.Driver")
             DB_SCHEMA=public;;
     "oracle.jdbc.driver.OracleDriver")
             DB_SCHEMA=$DB_USER;;
     *)
         $INFOTEXT "Unkown database with driver $DB_DRIVER";
         exit 1;;
   esac
   dummy=$DB_SCHEMA
   $INFOTEXT -n "\nPlease enter the name of the database schema [$dummy] >> "
   DB_SCHEMA=`Enter $dummy`
}


#############################################################################
# Query the parameters for a postgreSQL db connection
#############################################################################
queryPostgres()
{
   DB_SCHEMA=public
   DB_DRIVER="org.postgresql.Driver"
   queryDB postgresql 5432
   DB_URL="jdbc:postgresql://$DB_HOST:$DB_PORT/$DB_NAME"
}

#############################################################################
# Query the parameters for the oracle db connection
#############################################################################
queryOracle()
{
   DB_SCHEMA=arco_write
   DB_DRIVER="oracle.jdbc.driver.OracleDriver"
   queryDB oracle 1521
   DB_URL="jdbc:oracle:thin:@$DB_HOST:$DB_PORT:$DB_NAME"
}



# ----------------------------------------------------------------
#  echo the sqlUtil command for connecting to the database
#  to stdout
#  Uses the variables DB_DRIVER DB_URL DB_USER and DB_PW
# ----------------------------------------------------------------
echoConnect() {
   echo "debug SEVERE"
   echo "connect $DB_DRIVER $DB_URL $DB_USER $DB_PW"
   echo "exit"
}


# ----------------------------------------------------------------
#  Run the sqlUtil
# ----------------------------------------------------------------
sqlUtil() {
  #$INFOTEXT "\nClasspath for sqlUtil ---------------------------"
  #$INFOTEXT "$CP"
  #$INFOTEXT " finished classpath -------------------------------"
  $JAVA_HOME/bin/java -classpath  $CP com.sun.grid.util.SQLUtil
  return $?
}

searchJDBCDriverJar()
{
   DRIVER=`echo $1 | sed 's/\./\//g'`
   while :
   do
      $INFOTEXT -n "\nSearch for the jdbc driver $1 \nin directory $2 "
      for i in $2/*.jar; do
         $INFOTEXT -n "."
         $JAVA_HOME/bin/jar tf $i | grep $DRIVER > /dev/null
         if [ $? -eq 0 ]; then
            $INFOTEXT "\nfound in $i"
            #$INFOTEXT "add $i to classpath"
            CP="$i:$CP"            
            return 0
         fi
      done
      $INFOTEXT "jdbc driver $i not found in any jar file of directory $2"
      $INFOTEXT "Please copy your driver jar into the directory $2"
      $INFOTEXT -n "Press enter to continue >> " 
      Enter
   done
}

# ---------------------------------------------------------------
# testDB
# Try to connect to the database
#
# Parameters:
#
#     $1   base directory of the installation
#          if this parameter is set the database version will be 
#          queried and updated.
#
# return codes    0    => connection OK
#                 else => connection Failed
# ---------------------------------------------------------------
testDB() {
   
  $INFOTEXT -ask y n -def y -n \
            "\nShould the connection to the database be tested? (y/n) [y] >> "
  dummy=$?
  if [ $dummy -eq 0 ]; then
     $INFOTEXT -n "\nTest db connection to '$DB_URL' ... "
     echoConnect | sqlUtil 2> /dev/null
     dummy=$?
     if [ $dummy -eq 0 ]; then
       $INFOTEXT "OK"
       if [ "$1" != "" ]; then
          testDBVersion $1
          dummy=$?
       else 
         dummy=0
       fi
     else
       $INFOTEXT "Failed ($dummy)"
     fi
  else
     $INFOTEXT "Skip the database connection test"
     dummy=0
  fi
  return $dummy 
}

# -------------------------------------------------
# echo the commands for the sql util to stdout
# which queries the version of the dbmodel
#
#  Uses the variables DB_DRIVER, DB_URL, DB_USER, DB_PW
#  and DB_SCHEMA
# -------------------------------------------------
echoPrintDBVersion() {
   echo "debug SEVERE"
   echo "connect $DB_DRIVER $DB_URL $DB_USER $DB_PW"
   echo "debug INFO"
   echo "install print_db_version -only-id $DB_SCHEMA"
   echo "exit"
}

# ----------------------------------------------------------------
# query the version of the database model and do an upgrade.
# Paramters:
#    $1 base directory of the installation. In the subdirectory 
#       database/<database name> the file dbdefinition.xml is expected.
#
#  Return:
#          0  if the version of the database model is OK or the
#             the database model has been successfully updated.
# ----------------------------------------------------------------
testDBVersion() {
    $INFOTEXT -n "Query db version ... " 
    dummy=`echoPrintDBVersion | sqlUtil 2> /dev/null`

    case "$dummy" in
      "-1")     $INFOTEXT "no sge tables found";;
      [0-9]*) $INFOTEXT "found version $dummy";;
      *)        $INFOTEXT "error ($dummy)";
                return 1;;
    esac

    if [ $dummy -lt $DB_VERSION ]; then
       $INFOTEXT "New version of the database model is needed"
       
      case "$DB_DRIVER" in
        "org.postgresql.Driver")
                DB_DEF=$1/database/postgres/dbdefinition.xml;;
        "oracle.jdbc.driver.OracleDriver")
                DB_DEF=$1/database/oracle/dbdefinition.xml;;
        *)
            $INFOTEXT "Unkown database with driver $DB_DRIVER";
            exit 1;;
      esac
 
      installDB $DB_VERSION $DB_DEF
      return $?
    else 
      return 0
    fi
}       

# ----------------------------------------------------------------
#  echo the sqlUtil command for connecting to the database
#  and installing a dbmodel to stdout.
#  Uses the variables DB_DRIVER DB_URL DB_USER, DB_PW, DB_SCHEMA,
#  READ_USER
#
#  Parameters:
#     $1   id of the version which should be installed
#     $2   xml file with the definition if the dbmodel
# ----------------------------------------------------------------
echoInstall() {
   echo "debug SEVERE"
   echo "connect $DB_DRIVER $DB_URL $DB_USER $DB_PW"
   echo "debug INFO"
   if [ "$READ_USER" != "" ]; then
      echo "set READ_USER $READ_USER"
   fi
   echo "install $1 $2 $DB_SCHEMA"
   echo "exit"
}


# ----------------------------------------------------------------
#  Install or update the database model.
#  Parameters:
#     $1   id of the version which should be installed
#     $2   xml file with the definition if the dbmodel
# ----------------------------------------------------------------
installDB() {

   if [ $1 -gt 0 ]; then
      $INFOTEXT -n -ask y n -def y \
                "\nShould the database model be upgraded to version $1? (y/n) [y] >> "
      dummy=$?
   else
      $INFOTEXT -n -ask y n -def y \
                "\nShould the database model version $1 be installed? (y/n) [y] >> "
      dummy=$?
   fi
   
   if [ $dummy -eq 0 ]; then
   
      $INFOTEXT "\nThe ARCo web application connects to the database"
      $INFOTEXT "with a user which has restricted access."
      $INFOTEXT "The name of this database user is needed to grant"
      $INFOTEXT "him access to the sge tables."
      dummy=arco_read
      $INFOTEXT -n "\nPlease enter the name of this database user [$dummy] >> "
      READ_USER=`Enter $dummy`
   

      if [ $1 -gt 0 ]; then
         $INFOTEXT -n "Upgrade to database model version $1 ... "
      else
         $INFOTEXT -n "Install database model version $1 ... "
      fi
      
      
   
      echoInstall $1 $2 | sqlUtil 2> /dev/null
      dummy=$?
      if [ $dummy -eq 0 ]; then
        $INFOTEXT "OK"        
      else
        $INFOTEXT "Failed ($dummy)"
      fi
   else
      $INFOTEXT "Installation aborted"
      dummy=1
   fi
  return $dummy 
}




