##############################################################################################################
##    Script Name    : upgradeCMS.sh                                                                        ##
##    Author         : Leon Lin                                                                             ##
##    Created on     : 04/12/2013                                                                           ##
##    Usage          : ./upgradeCMS.sh ${init_script_path} ${restore_conf_script_path}                      ##
##    Purpose        : Back up of original CMS config and installed/updates to newer CMS                    ##
##                                                                                                          ##
##############################################################################################################
#!/bin/bash

#########################################################################################
# get init config script name
#########################################################################################
PARAMS=("$@")

echo ${PARAMS[0]}
echo ${PARAMS[1]}

if [[ ${#PARAMS[@]} > 2 ]]; then
	echo parameters "${PARAMS[*]}" invalid, only accepted 2 parameters.
	exit 1
else
	if [ ! -f ${PARAMS[0]} ]; then
		echo script "${PARAMS[0]}" doesn\'t exists
		exit 1
	fi

	if [ ! -f ${PARAMS[1]} ]; then
		echo script "${PARAMS[1]}" doesn\'t exists
		exit 1
	fi 
fi

INIT_SCRIPT=${PARAMS[0]}
POST_UPGRADE_SCRIPT=${PARAMS[1]}




#########################################################################################
# execute init configraution
#########################################################################################
. ${INIT_SCRIPT}


#########################################################################################
# Settings
#########################################################################################

START=$(date +%s)
TIMESTAMP=`date --utc -d "@$(( $START ))" +%Y%m%d_%H%M%S`
LOGPATH="/home/upgrade"
FULL_LOG="$LOGPATH/upgradeCMS_${CMS_FROM_VERSION}_to_${CMS_TO_VERSION}.$HOSTNAME.$TIMESTAMP.log"
YUM_REPO="/etc/yum.repos.d/upgrade.repo"
INSTALL_FROM_YUM=`cat ${CURRENT_PACKAGE_FOLDER}/conf/upgradeConf.properties | grep "upgrade.from.repo" | cut -d "=" -f 2`
YUM_REPO_SOURCE=`cat ${CURRENT_PACKAGE_FOLDER}/conf/upgradeConf.properties | grep "repo.path" | cut -d "=" -f 2`

#Get pipeline exit code
set -o pipefail

Color_Off='\e[0m'       # Text Reset
Black='\e[0;30m'        # Black
Red='\e[0;31m'          # Red
Green='\e[0;32m'        # Green
Yellow='\e[0;33m'       # Yellow
Blue='\e[0;34m'         # Blue
Purple='\e[0;35m'       # Purple
Cyan='\e[0;36m'         # Cyan
White='\e[0;37m'        # White

## Abort Loop
die() {
    printf -v f "\n\n%65s";printf "%s\n" "${f// /#}" 
    printf "Error: $1\n"
    printf "Please Review Log File $FULL_LOG\n"
    printf -v f "%65s";printf "%s\n" "${f// /#}" 
    printf "%-15s${Red}%-5s${Color_Off}\n\n\n" "Update Status: " "Failed!"
    exit 1
}

startupgrade  () {
    printf -v f "\n\n%65s";printf "%s\n" "${f// /#}" 
    printf "[`date -d @$(date +%s) +'%Y-%m-%d %H:%M:%S'`]\n"
    printf "Logging Update output to $FULL_LOG\n"
    printf "$1\n"
    printf -v f "%65s";printf "%s\n" "${f// /#}" 
}

stepduration () {
    printf -v f "\n%65s";printf "%s\n" "${f// /#}" 
    printf "[`date -d @$(date +%s) +'%Y-%m-%d %H:%M:%S'`]\n"
    printf "$1\n"
    printf "${Green}%-5s${Color_Off}\n" "Status: Success"
    printf "Step Duration [`date --utc -d "@$(( $(date +%s) - $STEP_START ))" +%T`]\n"
    printf -v f "%65s";printf "%s\n\n\n" "${f// /#}" 
}

totalduration  () {
    printf -v f "\n\n%65s";printf "%s\n" "${f// /#}" 
    printf "[`date -d @$(date +%s) +'%Y-%m-%d %H:%M:%S'`]\n"
    printf "Logging Update output to $FULL_LOG\n"
    printf "$1\n"
    printf "${Green}%-5s${Color_Off}\n" "Status: Success"
    printf "Total Update Duration [`date --utc -d "@$(( $(date +%s) - $START ))" +%T`]\n"
    printf -v f "%65s";printf "%s\n" "${f// /#}" 
}

#########################################################################################
# Create log folder if it does exists
#########################################################################################
if [[ ! -d "$LOGPATH" ]]; then
    mkdir $LOGPATH
    echo "Creating $LOGPATH"
    printf "${Green}%-5s${Color_Off}\n" "Done."    
fi

. ./getCommonBackupLocation.sh

( 

startupgrade "Starting CMS Application Upgrade from ${CMS_FROM_VERSION} to ${CMS_TO_VERSION}"

#########################################################################################
# Stop Service
#########################################################################################
STEP_START=$(date +%s)
for i in "${!SERVICE[@]}"
do
    if [[ -e /etc/init.d/${SERVICE[i]} ]] ; then 
    echo "Service ${SERVICE[i]} exists"
    echo "Stopping ${SERVICE[i]} prior to system update"
    service ${SERVICE[i]} stop
    else
    echo "Service ${SERVICE[i]} not installed on system"
    fi
done
stepduration "Completed stopping all services"

#########################################################################################
# Create upgrade repository if it does not exists
#########################################################################################

if [ ${INSTALL_FROM_YUM} == 'yes' ]; then
while [[ $CORRECT != "y" ]] && [[ -z $YUM_REPO_SOURCE ]]
do
    printf "Checking for Upgrade Repository\n"
    if [ ! -f ${YUM_REPO} ] ; then
        printf "%-50s\n" "Upgrade Repository not found, Please Enter Repository URL"
        printf "%-50s\n" "Examples:"
        printf "%-50s\n" "  http://www.my-repository.com/software/"
        printf "%-50s\n" "  ftp://www.my-repository.com/software/"
        printf "%-50s\n" "  file:///mnt/cdrom/"
        printf           "Enter Repository URL: "
        
        while [[ -z $YUM_REPO_SOURCE ]] ; do
        read YUM_REPO_SOURCE
        regex='(https?|ftp|file)://[-A-Za-z0-9\+&@#/%?=~_|!:,.;]*[-A-Za-z0-9\+&@#/%=~_|]'
            if [[ $YUM_REPO_SOURCE =~ $regex ]] ; then
                YUM_REPO_SOURCE=$YUM_REPO_SOURCE
            else [[ $YUM_REPO_SOURCE == "" ]]
                printf "Invalid Repository URL, Please enter again:"
                YUM_REPO_SOURCE=""
            fi
        done
    else
        YUM_REPO_SOURCE=`cat /etc/yum.repos.d/upgrade.repo |grep "baseurl" | awk -F= '{print $2}'`
    fi
    printf "%-50s\n" "Repository URL is $YUM_REPO_SOURCE"
    printf "Is this correct? [y/n] "
    read CORRECT
    if [[ $CORRECT != "y" ]] ; then
        YUM_REPO_SOURCE=""
        if [[ -f $YUM_REPO ]] ; then
            rm  $YUM_REPO
        fi
    fi
done

if [[ ! -f ${YUM_REPO} ]] || [[ $YUM_REPO_SOURCE != "`cat /etc/yum.repos.d/upgrade.repo |grep "baseurl" | cut -d "=" -f 2`" ]];then
	printf "%-45s\n" "Creating Upgrade $YUM_REPO"
	echo "[Upgrade_Repository]"     >> ${YUM_REPO}
	echo "name=Upgrade Repository"  >> ${YUM_REPO}
	echo "baseurl=$YUM_REPO_SOURCE" >> ${YUM_REPO}
	echo "enabled=1"                >> ${YUM_REPO}
	echo "gpgcheck=0"               >> ${YUM_REPO}
fi

echo "Installing upgrade from repo ${YUM_REPO_SOURCE}"

#########################################################################################
# Check Dependencies of RPMs being installed
#########################################################################################
STEP_START=$(date +%s)
yum clean all
yum deplist ${BASE_PACKAGES} ${ACC_PACKAGES} ${APP_PACKAGES} > yum_deplist.log
if [[ -n `cat yum_deplist.log | grep "Unsatisfied dependency"` ]] ; then
    die "Missing: Dependencies; Review yum_deplist.log"
fi
stepduration "Completed Checking yum Dependencies"
fi


#########################################################################################
# Backup Configuration Files
#########################################################################################
STEP_START=$(date +%s)
printf "%-7s" "Backing up config Files:"
BACKUP_DIR="/tmp/backup"
BACKUP_FILE="upgrade_conf_backup.tar"

if [ ! -d ${BACKUP_DIR} ];then
	mkdir -p ${BACKUP_DIR}
fi

tar -cvf ${BACKUP_DIR}/${BACKUP_FILE} ${CONFIG_FILES[@]}
stepduration "Completed Backing up of Old Config Files"


#########################################################################################
# Backup orginal cms directory/files
#########################################################################################
#STEP_START=$(date +%s)
#printf "%-7s" "Backing up cms Files:"
#BACKUP_DIR="/tmp/backup"
#EXCLUDES_FILE_PATH=""
#tar czvf $backupTarFilePath --exclude-from=$excludes_file_path




#########################################################################################
# Cleanup removed Files 
#########################################################################################
STEP_START=$(date +%s)
cms_root="/opt/tandbergtv/cms"
echo "Cleaning up Legacy Files and Directory"
for i in "${!CLEANUP[@]}" ; do
    if [[ -f "$cms_root${CLEANUP[i]}" ]]; then
        rm -rvf "$cms_root${CLEANUP[i]}"
    elif [[ -d "$cms_root${CLEANUP[i]}" ]]; then
        rm -rvf "$cms_root${CLEANUP[i]}"
    else
        echo "" > /dev/null 2>&1
    fi
done
stepduration "Completed Cleaning up Legacy Files and Directory"

#########################################################################################
# Remove problematic RPMs
#########################################################################################
STEP_START=$(date +%s)
erase_rpm=`rpm -qa | grep cms-upgrade-2.5`
if [ -n "$erase_rpm" ] ; then
    rpm -e $erase_rpm
fi
stepduration "Completed Removal of Problematic RPMs"

#########################################################################################
# If rPath found remove it
#########################################################################################
STEP_START=$(date +%s)
if [ -x /usr/bin/conary ] ; then
    printf "%-45s" "Removing Conary:"
    conary erase iconfig
    conary erase conary-cim-configuration
    conary erase conary-cim rpath-tools
    conary erase conary
    printf "${Green}%-5s${Color_Off}\n" "Done."
else
    echo "Conary Not Installed"
fi
stepduration "Completed Removing Conary"

#########################################################################################
# Check if prepack rpm exists then remove it first
#########################################################################################


STEP_START=$(date +%s)
printf "%-45s\n" "Removing prepack rpms:"
PREPACK_RPMS="file-subsystem-enhancement
	      configurations
	      cablelabs-vod-1.1-metadata-parser
	      adi-1.1-isa"

for RPM_NAME in ${PREPACK_RPMS[*]};
do
	CHECK_PREPACK_RPM=`rpm -qa | grep ${RPM_NAME}`
	if [ ! -z "$CHECK_PREPACK_RPM" ] ; then
	    printf "found rpm ${RPM_NAME}, removing..."
	    rpm -e $RPM_NAME 2>&1 || die "Failed: Unable to remove prepack rpms"
	    printf "%-45s\n" "done"
	fi
done

stepduration "Completed Removing prepack rpms"

#The symbolic link removed with prepack configuration package, need to fix it before restore files.
if [ ! -d "/opt/tandbergtv/cms/jboss" ];then
echo "fix symbolic link for Jboss home"
ln -svf /opt/tandbergtv/cms/jboss-*.GA /opt/tandbergtv/cms/jboss
stepduration "Completed Updating Symbolic Link for Jboss home"
fi

if [ ! -d "/opt/tandbergtv/watchpoint/tomcat" ];then
echo "fix symbolic link for Tomcat home"
ln -svf /opt/tandbergtv/watchpoint/tomcat-* /opt/tandbergtv/watchpoint/tomcat
stepduration "Completed Updating Symbolic Link for Tomcat home"
fi

#########################################################################################
# Updating Existing System Packages
#########################################################################################

if [ ${INSTALL_FROM_YUM}=="yes" ]; then
	STEP_START=$(date +%s)
	printf "%-45s\n" "Updating Existing System Packages:"
	yum update -v -d 10 --assumeyes                   2>&1 || die "Missing: System RPMs Not Found In Repository"
	stepduration "Completed Updating Existing System Packages"


#########################################################################################
# Installing New System and Appliance Packages
#########################################################################################
	if [ ${#BASE_PACKAGES[@]} -ne 0 ] && [[ ${BASE_PACKAGES[0]} != "" ]];then
		STEP_START=$(date +%s)
		printf "%-45s\n" "Installing New System and Appliance Packages:"
		yum install -v -d 10 --assumeyes ${BASE_PACKAGES} 2>&1 || die "Missing: System RPMs Not Found In Repository"
		stepduration "Completed Installing New System and Appliance Packages"
	fi

	## Install 3rd Party RPMs
	if [ ${#ACC_PACKAGES[@]} -ne 0 ] && [[ ${ACC_PACKAGES[0]} != "" ]];then	
		STEP_START=$(date +%s)
		yum install -v -d 10 --assumeyes ${ACC_PACKAGES}  2>&1 || die "Missing: 3rd Party RPMs Not Found In Repository"
		stepduration "Completed Installing 3rd Party Packages"
	fi

	## Install App
	if [ ${#APP_PACKAGES[@]} -ne 0 ] && [[ ${APP_PACKAGES[0]} != "" ]];then
		STEP_START=$(date +%s)
		#rm /opt/tandbergtv/cms/jboss
		#rm /opt/tandbergtv/watchpoint/tomcat
		yum install -v -d 10 --assumeyes ${APP_PACKAGES}  2>&1 || die "Missing: Appliance RPMs Not Found In Repository"
	fi

	printf "${Green}%-5s${Color_Off}\n" "Done."
	stepduration "Completed Installing Appliance Packages"
else
#########################################################################################
# Installing new packages from rpm directory
#########################################################################################
	rpm -ivh ${PACKAGE_RPM_FOLDER}/*.rpm 2>&1 || die "Failed: Unable to install rpms from rpm folder"
fi

#########################################################################################
# Update Service Start Order
#########################################################################################
STEP_START=$(date +%s)
for i in "${!SERVICE[@]}"
do
    if [[ -e /etc/init.d/${SERVICE[i]} ]] ; then 
    echo "Service ${SERVICE[i]} exists"
    echo "Updating start order for ${SERVICE[i]}"
    chkconfig --add ${SERVICE[i]}
    chkconfig ${SERVICE[i]} on
    else
    echo "Service ${SERVICE[i]} not installed on system"
    fi
done
stepduration "Completed Updating Services Startup Order"

#########################################################################################
# Post Upgrade Fixs 
#########################################################################################
STEP_START=$(date +%s)
echo "Updating symbolic link for java"
ln -svf /usr/java/default/bin/java /usr/bin/java
stepduration "Completed Updating Symbolic Link for java"


STEP_START=$(date +%s)
echo "Clearing JacOrb cache"
find /opt/tandbergtv/cms/jboss/bin -name "_nsdb_*" -exec rm -rvf {} \;
stepduration "Completed Clearing JacOrb cache"


#########################################################################################
# Merge/Update/Restore Config Files 
#########################################################################################
. ./restoreCustomization.sh

#Restore conf files
STEP_START=$(date +%s)
printf "%-45s\n" "Restoring configuration files"
tar -vxf ${BACKUP_DIR}/${BACKUP_FILE} -C / || die"Failed: Unable to recover configuration files"
stepduration "Completed restoring configuration files"


#Post upgrade
STEP_START=$(date +%s)
printf "%-45s\n" "Executing post upgrade script"
. ${POST_UPGRADE_SCRIPT}
stepduration "Completed executing post upgrade script"

# Add history directory to common backup
HISTORY_DIR="r:/opt/tandbergtv/cms/workflow/history"
CB_DIR_FILE=/usr/local/platform/backup/conf/cms/cms_directories.txt
grep $HISTORY_DIR $CB_DIR_FILE 2>/dev/null || echo $HISTORY_DIR $CB_DIR_FILE

#Post upgrade
STEP_START=$(date +%s)
printf "%-45s\n" "Executing verifing script"
cd ${UPGRADE_HOME}
. ./verifyUpgrade.sh
stepduration "Completed executing verifing script"

totalduration "Finished Updating Appliance"

) 2>&1 | tee -a ${FULL_LOG}
