#!/bin/sh
#######################################################################################
##                                                                                   ##
##          Script Name : cmsdb_upgrade.sh                                           ##
##          Purpose     : Script to upgrade CMS database from 1.2/2.0/2.5 to 3.1     ##
##          Created by  : Suresh Neravati                                            ##
##          Created on  : 04/04/2013                                                 ##
##                                                                                   ##
#######################################################################################
UPGRD_DIR="/home/upgrade/db_upgrade"
TIMESTAMP=`date +%Y%m%d_%H%M%S`
LATEST_DBVER="3.4.12"
RUN_MODE="$1"
DBVER=$(su - oracle -c "sqlplus -S /nolog<<SQ1
  connect / as sysdba
  set pages 0
  set feedback off
  SELECT setting_value FROM WFS.SYSTEM_SETTINGS WHERE setting_type = 'RELEASE';
  exit
SQ1"
)

# Run the scripts restore and upgrade
(
case "${DBVER}" in
   "3.2.22" )
echo -e "\nUpgrading CMS 2.5 database to CMS 3.1, please wait...!\n"
sh ${UPGRD_DIR}/cms_direct_inplace_upgrade/cmsdb_inplace_upgrade.sh
if [ -d "/home/oracle/scripts/install/installcms" ]; then
   sh ${UPGRD_DIR}/cms_direct_inplace_upgrade/cmsdb_upgrade_evolve.sh Y Y Y ${DBVER} ${LATEST_DBVER}
fi
       ;;
   "3.3.20"  )
echo -e "\nUpgrading CMS 3.0 database to CMS 3.1, please wait...!\n"
sh ${UPGRD_DIR}/cms_direct_inplace_upgrade/cmsdb_inplace_upgrade.sh
if [ $? -eq 0  ]; then
   sh ${UPGRD_DIR}/cms_direct_inplace_upgrade/cmsdb_upgrade_evolve.sh Y N N ${DBVER} ${LATEST_DBVER}
fi
       ;;
   ${LATEST_DBVER} ) 
TTLCNT=$(su - oracle -c "sqlplus -S /nolog<<ZYX
  connect / as sysdba
  set pages 0
  set feedback off
  select count(*) from wfs.pmm_title;
  exit
ZYX"
)
if ((${TTLCNT} == 0)); then
#copy the scripts to oracle folder
cp -r ${UPGRD_DIR}/cms_direct_upgrade /home/oracle/scripts/
if [ $? -ne 0 ]; then
  echo -e "\nError in copying the cms database upgrade script files,"
  echo "Exiting the script...\n"
  exit 1
else
  #Change ownership and executable 
  chown -R oracle:oinstall /home/oracle/scripts/cms_direct_upgrade
  chmod -R 744 /home/oracle/scripts/cms_direct_upgrade
  su - oracle -c "/home/oracle/scripts/cms_direct_upgrade/cms_direct_upgrade.sh ${LATEST_DBVER} ${RUN_MODE}"
fi
else
   echo -e "Database upgrade script already ran on this server. Exiting from the script execution ... "
   exit 1
fi
       ;;
   * ) 
       echo -e "You can't run the upgrade script on this server.\n"
       exit 1
esac

) 2>&1 | tee cmsdb_upgrade_$TIMESTAMP.log

