#!/bin/sh
# 1. copy configuration/template files and JDBC drivers.
# 2. update the database schema.

if [ ! -f upgrade.jar ]; then 
echo "Error: this program must be run in the directory misc/upgrade"
exit 1
fi

HOME_PRE=$@
if [ "$HOME_PRE" = "" ] ; then
   echo "Usage: upgrade path-to-the-installed-running-bugzero-home"
   echo "   Ex: upgrade /usr/tomcat/webapps/bugzero"
exit 1
fi

CONF_PRE=$HOME_PRE/WEB-INF/classes/conf
if [ ! -d "$CONF_PRE" ]; then
   echo "Bugzero home is not entered correctly, no conf dir was found."
exit 1
fi

LIB_PRE=$HOME_PRE/WEB-INF/lib
if [ ! -d "$LIB_PRE" ]; then
   echo "Bugzero home is not entered correctly, no lib dir was found."
exit 1
fi

TEMPLATE_PRE=$HOME_PRE/WEB-INF/classes/template
if [ ! -d "$TEMPLATE_PRE" ]; then
   echo "Bugzero home is not entered correctly, no template dir was found."
exit 1
fi

CONF_DIR=../../classes/conf/.
LIB_DIR=../../lib/.
TEMPLATE_DIR=../../classes/template/.

cp -f "$CONF_PRE"/system.properties $CONF_DIR
cp -f "$CONF_PRE"/db.properties $CONF_DIR
cp -f "$CONF_PRE"/mail.properties $CONF_DIR
cp -f "$TEMPLATE_PRE"/email_subject $TEMPLATE_DIR
cp -f "$TEMPLATE_PRE"/email_body $TEMPLATE_DIR

if [ -f "$TEMPLATE_PRE"/reminder_subject ]; then
  cp -f "$TEMPLATE_PRE"/reminder_subject $TEMPLATE_DIR
fi
if [ -f "$TEMPLATE_PRE"/reminder_body ]; then
  cp -f "$TEMPLATE_PRE"/reminder_body $TEMPLATE_DIR
fi
if [ -f "$CONF_PRE"/schedule.properties ]; then
  cp -f "$CONF_PRE"/schedule.properties $CONF_DIR
fi

errorlevel=$?
if [ $errorlevel = 0 ]; then
for i in "$LIB_PRE"/*.*; do
if [ "$i" != "$LIB_PRE/bugzero.jar" ]; then
if [ "$i" != "$LIB_PRE/mail.jar" ]; then
if [ "$i" != "$LIB_PRE/activation.jar" ]; then
if [ "$i" != "$LIB_PRE/mysql.jar" ]; then
if [ "$i" != "$LIB_PRE/mysql-connector-java-3.0.8-stable-bin.jar" ]; then
if [ "$i" != "$LIB_PRE/mysql-connector-java-3.0.15-ga-bin.jar" ]; then
   cp -f "$i" $LIB_DIR
fi
fi
fi
fi
fi
fi
done
errorlevel=$?
fi

if [ $errorlevel != 0 ]; then
  echo "////////////////////////////////////////////////////////////////////"
  echo "Failed to copy required files, you may need do it manually"
  echo "..................................... and then run checkdb"
else 
# remove the mail.jar and activation.jar if the original ones are not present.
  if [ ! -f "$LIB_PRE/mail.jar" ]; then
    rm -f "$LIB_DIR/mail.jar"
  fi
  if [ ! -f "$LIB_PRE/activation.jar" ]; then
    rm -f "$LIB_DIR/activation.jar"
  fi

  echo "Now updating the database schema ...."
  sh checkdb.sh
fi

