#!/bin/bash
# This script is for iPortal to upgrade from old version to new version.
#
# First of all, you should to set two variables :
# OLD_PKG : point to the absolute path of old version iPortal's root directory, and it should not end with "/"
# NEW_PKG : point to the absolute path of new version iPortal's root directory, and it should not end with "/"
#
set -e

read -p "Please enter old version package path : "  OLD_PKG
read -p "Please enter new version package path : "  NEW_PKG


# check old version package is exist or not
if [ ! -d "$OLD_PKG" ];then
  echo "$OLD_PKG is not exist! Make sure OLD_PKG is set correctly!";
  exit 1;
fi
# check necessary authority : read
if [ ! -r "$OLD_PKG" ];then
  echo "Current user has no permission to read the $OLD_PKG, try with the higher authority for the user again!";
  exit 1;
fi

# check new version package is exist or not
if [ ! -d "$NEW_PKG" ];then
  echo "$NEW_PKG is not exist! Make sure NEW_PKG is set correctly!";
  exit 1;
fi

# check necessary authority : write
if [ ! -w "$NEW_PKG" ];then
  echo "Current user has no permission to write the $NEW_PKG, try with the higher authority for the user again!";
  exit 1;
fi

# backup conf and webapps of new version package, and crete tmp directory in order to store datas of old version package
echo "Backup $NEW_PKG/conf ..."
cd $NEW_PKG
mkdir $NEW_PKG/tmp

OLD_PKG_APP_HOME=$OLD_PKG/webapps
NEW_PKG_APP_HOME=$NEW_PKG/webapps

# check if the old version enabled proxy
if [ -d "$OLD_PKG/webapp" ];then
  OLD_PKG_APP_HOME=$OLD_PKG/webapp
fi

cp -rf $OLD_PKG/conf/server.xml $NEW_PKG/conf
cp -rf $OLD_PKG/conf/web.xml $NEW_PKG/conf

# cover logs and temp of new version with logs of old version
cp -rf $OLD_PKG/logs $NEW_PKG

# copy iserver of old version to tmp of new version
cp -r $OLD_PKG_APP_HOME/iserver $NEW_PKG/tmp

rm -rf $NEW_PKG/tmp/iserver/font
rm -rf $NEW_PKG/tmp/iserver/META-INF
rm -rf $NEW_PKG/tmp/iserver/resources
rm -rf $NEW_PKG/tmp/iserver/output/temp

rm -rf $NEW_PKG/tmp/iserver/WEB-INF/lib
rm -rf $NEW_PKG/tmp/iserver/WEB-INF/worker-lib
rm -f $NEW_PKG/tmp/iserver/WEB-INF/urlrewrite.xml

# cover iserver of new version with tmp\iserver
cp -rf $NEW_PKG/tmp/iserver/WEB-INF $NEW_PKG_APP_HOME/iserver
cp -rf $NEW_PKG/tmp/iserver/templates/webprinting-layouts $NEW_PKG_APP_HOME/iserver/templates

# delete tmp
rm -rf $NEW_PKG/tmp

echo "Congratulations! Upgrade success!"

