#!/bin/bash
#####################################################################################
# 						FreePBX 10.13.66-1 Upgrade	                            	#
#####################################################################################
# ISSUES
# FREEPBX-8695 - Update to SHMZ 6.6
# FREEPBX-8950 - Update to FreePBX 13
# FREEPBX-8937 - Update MOTD
#####################################################################################
# Copyright 2015 Sangoma US Inc.  This upgrade script and all concepts are property of
# Schmooze Com, Inc. and are not to be copied for other use.  This upgrade script is free
# to use for upgrading FreePBX Distro systems only but carries no guarnatee on performance
# and is used at your own risk.  This script carries NO WARRANTY.
#####################################################################################
asterisk=`/usr/sbin/asterisk -rx "core show version"`
kernel=`uname -a`
version=`cat /etc/schmooze/pbx-version`
brand=`cat /etc/schmooze/pbx-brand`
host=`hostname`
upgradeversion=10.13.66-1
#####################################################################################
# Check to make sure this is a FreePBX Distro system before executing
echo "Check to make sure this is a FreePBX Distro system before executing"
if [ -f /etc/asterisk/freepbxdistro-version ]; then
	echo "This appears to be a FreePBX Distro system as it has a FreePBX Distro Version of $version"
	echo "`date` This appears to be a FreePBX Distro system as it has a FreePBX Distro Version of $version" >> /var/log/pbx/upgrade/"$upgradeversion"
else
	if [ -f /etc/schmooze/pbx-version ]; then
		echo "This appears to be a FreePBX Distro system as it has a Distro Version of $version"
		echo "`date` This appears to be a FreePBX Distro system as it has a Distro Version of $version" >> /var/log/pbx/upgrade/"$upgradeversion"
	else
		echo "This does not appears to be a FreePBX Distro system as it has no Distro Version file"
		exit
	fi
fi
#####################################################################################
#Echo in some settings into the log file for recording keeping.
echo "VARIABLES SET FOR UPGRADE" >> /var/log/pbx/upgrade/"$upgradeversion"
echo "	asterisk=$asterisk" >> /var/log/pbx/upgrade/"$upgradeversion"
echo "	kernel=$kernel" >> /var/log/pbx/upgrade/"$upgradeversion"
echo "	version=$version" >> /var/log/pbx/upgrade/"$upgradeversion"
echo "	host=$host" >> /var/log/pbx/upgrade/"$upgradeversion"
echo "	upgradeversion=$upgradeversion" >> /var/log/pbx/upgrade/"$upgradeversion"
echo "	virtual=$virtual" >> /var/log/pbx/upgrade/"$upgradeversion"
echo "" >> /var/log/pbx/upgrade/"$upgradeversion"
# Try to use the new SSA, if it exists
if [ -e /var/www/html/admin/modules/sysadmin/hooks/update-system ]
then
	SSA=/var/www/html/admin/modules/sysadmin/hooks/update-system
else
	SSA=/usr/sbin/sysadmin_update_system
fi
###########################################################################
# Define our logger function for use later (this is needed early in the
# script for people who are running it interactively, rather than batched
function elog {
	echo "$1"
	$SSA -v$upgradeversion -sm"$1"
}

###########################################################################
# Check if this is a cluster
if [ -f /usr/sbin/pcs ]; then
	PCS=$(/usr/sbin/pcs property)
	CLUSTERVERS=$(echo "$PCS" | grep dc-version | awk ' { print $2 }')
	if [ "$CLUSTERVERS" ]; then
		elog "Cluster detected!"
		# We're a cluster member, we can continue only if
		# this node is in standby, or, if the entire cluster
		# is in maintanance mode

		# If this node is in standby mode, we can continue.
		STANDBY=$(echo "$PCS" | grep "$(hostname): standby=on")
		if [ "$STANDBY" ]; then
			elog "This node ($(hostname)) is in standby. Continuing"
			CONTINUEOK=true
		else
			MAINT=$(echo "$PCS" | grep "maintenance-mode: true")
			if [ "$MAINT" ]; then
				elog "Cluster in maintanance mode. Continuing"
				CONTINUEOK=true
			fi
		fi
		if [ ! "$CONTINUEOK" ]; then
			elog "***************************"
			elog "* THIS MACHINE IS PART OF *"
			elog "* OF A HA CLUSTER, AND IS *"
			elog "* NOT CORRECTLY PREPARED. *"
			elog "***************************"
			elog "** FAILURE TO FOLLOW THE **"
			elog "** HA WIKI UPGRADE GUIDE **"
			elog "** WILL CAUSE AN OUTAGE. **"
			elog "***************************"
			elog ""
			elog "Full instructions are available at: "
			elog "  http://j.mp/pbxupgrade"
			$SSA -unlock
			exit
		fi
	fi
fi
###########################################################################
#Upgrade to new $upgradeversion Base
echo
echo "Your FreePBX Distro System is being upgraded to $upgradeversion. Please standby..."
echo "`date` Your FreePBX Distro System is being upgraded to $upgradeversion. Please standby..." >> /var/log/pbx/upgrade/"$upgradeversion"
echo "" >> /var/log/pbx/upgrade/"$upgradeversion"
echo
###########################################################################
# Setup tmp file for backup of anythign we need to copy before upgrading.
mkdir -p /usr/tmp/$upgradeversion
mkdir -p /etc/schmooze
chown -R asterisk:asterisk /etc/schmooze
################################################# STAGE 1 STARTING - GUI MODULES ####################################
echo
echo "STAGE 1 STARTING - GUI Modules"
echo "`date` STAGE 1 STARTING - GUI Modules" >> /var/log/pbx/upgrade/"$upgradeversion"
echo
$SSA -s -v$upgradeversion -i300
###########################################################################
# Upgrade All FreePBX GUI Modules
echo
echo " Upgrade All FreePBX GUI Modules"
echo " `date` Upgrade All FreePBX GUI Modules" >> /var/log/pbx/upgrade/"$upgradeversion"
echo
# Change Permission of amportal.conf
chown asterisk:asterisk /etc/amportal.conf
# Fix permissions before doing anything else
if [ -e /usr/sbin/fwconsole ]; then
	/usr/sbin/fwconsole chown
else
	/usr/local/sbin/amportal chown
fi

# At this point, if we're running FreePBX 13, fwconsole exists
# (as amportal chown would have put it in place). However, it
# may be in /usr/local/sbin/fwconsole. If that exists, make
# sure it's linked to /usr/sbin/fwconsole for compatibility.

if [ ! -e /usr/sbin/fwconsole ]; then
	[ -e /usr/local/sbin/fwconsole ] && ln -s /usr/local/sbin/fwconsole /usr/sbin/fwconsole
fi

# Installing all new modules for 12 now.  Running it a few times to make sure we get all the modules.
sudo -u asterisk /var/lib/asterisk/bin/module_admin installall
sudo -u asterisk /var/lib/asterisk/bin/retrieve_conf
sudo -u asterisk /var/lib/asterisk/bin/module_admin reload
sudo -u asterisk /var/lib/asterisk/bin/module_admin installall
sudo -u asterisk /var/lib/asterisk/bin/retrieve_conf
sudo -u asterisk /var/lib/asterisk/bin/module_admin reload
###########################################################################
echo
echo "STAGE 1 COMPLETED - GUI Modules - Moving to Stage 2"
echo "`date` STAGE 1 COMPLETED - GUI Modules - Moving to Stage 2" >> /var/log/pbx/upgrade/"$upgradeversion"
echo "" >> /var/log/pbx/upgrade/"$upgradeversion"
echo
$SSA -s -v$upgradeversion -i310
######################## STAGE 2 STARTING - RPM's #########################
echo
echo "STAGE 2 STARTING - RPMs"
echo "`date` STAGE 2 STARTING - RPM's" >> /var/log/pbx/upgrade/"$upgradeversion"
echo
$SSA -s -v$upgradeversion -i320
###########################################################################
echo
echo " Replace repos with only FreePBX Distro since some people have added other repos which can break updates"
echo " `date` Replace repos with only FreePBX Distro since some people have added other repos which can break updates" >> /var/log/pbx/upgrade/"$upgradeversion"
echo
rm -rf /etc/yum.repos.d/*
/bin/cat <<'EOTT' >/etc/yum.repos.d/FreePBX.repo
# PBX-Base.repo
#
# If the mirrorlist= does not work for you, as a fall back you can try the
# remarked out baseurl= line instead.
#
#base packages of the OS
[base]
name=SHMZ-6.6 - Base
mirrorlist=http://mirrorlist.freepbxdistro.org/?release=6.6&arch=$basearch&repo=os
#baseurl=http://yum.freepbxdistro.org/shmz-os/6.6/os/$basearch/
gpgcheck=0
enabled=1

#released updates
[updates]
name=SHMZ-6.6 - Updates
mirrorlist=http://mirrorlist.freepbxdistro.org/?release=6.6&arch=$basearch&repo=updates
#baseurl=http://yum.freepbxdistro.org/shmz-os/6.6/updates/$basearch/
gpgcheck=0
enabled=1

#additional packages that may be useful
[extras]
name=SHMZ-6.6 - Extras
mirrorlist=http://mirrorlist.freepbxdistro.org/?release=6.6&arch=$basearch&repo=extras
#baseurl=http://yum.freepbxdistro.org/shmz-os/6.6/extras/$basearch/
gpgcheck=0
enabled=1

#Core PBX Packages
[pbx]
name=pbx
mirrorlist=http://mirrorlist.freepbxdistro.org/?pbxver=6.13.66&release=6.6&arch=$basearch&repo=pbx
#baseurl=http://yum.freepbxdistro.org/pbx/6.13.66/$basearch/
gpgcheck=0
enabled=1

#Schmooze Commercial Packages
[schmooze-commercial]
name=schmooze-commercial
mirrorlist=  http://mirrorlist.schmoozecom.net/?release=6.6&arch=$basearch&repo=schmooze-commercial
#baseurl=http://yum.schmoozecom.net/schmooze-commercial/$release/$basearch/
gpgcheck=0
enabled=1

#High Availability Packages
[high-availability]
name=high-availability
#mirrorlist= http://mirrorlist.schmoozecom.net/?release=6.6&arch=$basearch&haver=r1&repo=high-availability
baseurl= http://yum.schmoozecom.net/high-availability/6/r1/$basearch/
gpgcheck=0
enabled=0

EOTT
###########################################################################
echo
echo "Clean Yum just to make sure we have a fresh list"
echo
yum clean all
###########################################################################
echo
echo "Moving to Next Step"
echo
###########################################################################
# Cleanup old Kernels to make space in boot
echo " Cleanup old Kernels to make space in boot"
echo " `date` Cleanup old Kernels to make space in boot" >> /var/log/pbx/upgrade/"$upgradeversion"
yum -y install yum-utils
package-cleanup -y --oldkernels --count=1
###########################################################################
echo
echo "Moving to Next Step"
echo
###########################################################################
# FREEPBX-8695- Update to SHMX 6.6
echo " Update to SHMZ 6.6 RPM's"
echo " `date` Update to SHMZ 6.6 RPM's" >> /var/log/pbx/upgrade/"$upgradeversion"
yum -y update
rm -rf /etc/yum.repos.d/Cent*
###########################################################################
echo
echo "Moving to Next Step"
echo
###########################################################################
# Install easyrsa3
yum -y install easyrsa3
###########################################################################
echo
echo "Moving to Next Step"
echo
###########################################################################
# Sysadmin would have been updated in the previous step. This means,
# As of now, we can stop using /usr/sbin/sysadmin_update_system, and
# use the new hook updater.
SSA=/var/www/html/admin/modules/sysadmin/hooks/update-system
echo
echo "STAGE 2 COMPLETED - RPM's - Moving to Stage 3"
echo "`date` STAGE 2 COMPLETED - Misc Items - Moving to Stage 4" >> /var/log/pbx/upgrade/"$upgradeversion"
echo "" >> /var/log/pbx/upgrade/"$upgradeversion"
$SSA -s -v$upgradeversion -i330
########################## STAGE 2 COMPLETED - RPM's ######################

################## STAGE 3 STARTING - MISC ITEMS  #########################
echo
echo "STAGE 3 STARTING - Misc Items"
echo "`date` STAGE 3 STARTING - Misc Items" >> /var/log/pbx/upgrade/"$upgradeversion"
echo
$SSA -s -v$upgradeversion -i340
###########################################################################
echo
echo "Moving to Next Step"
echo
###########################################################################
# FREEPBX-8950 - Update to FreePBX 13
echo " Removing outdated modules"
/var/lib/asterisk/bin/module_admin uninstall fw_ari
/var/lib/asterisk/bin/module_admin uninstall superfecta
/var/lib/asterisk/bin/module_admin uninstall fw_langpacks
/var/lib/asterisk/bin/module_admin uninstall accountcodepreserve
/var/lib/asterisk/bin/module_admin uninstall sng_mcu
rm -rf /var/www/html/admin/modules/fw_ari
rm -rf /var/www/html/admin/modules/superfecta
rm -rf /var/www/html/admin/modules/fw_langpacks
rm -rf /var/www/html/admin/modules/accountcodepreserve
rm -rf /var/www/html/admin/modules/sng_mcu
echo " Update to FreePBX 13"
/var/lib/asterisk/bin/freepbx_setting MODULEADMIN_SKIP_CACHE 1
echo " `date` Update to FreePBX 13" >> /var/log/pbx/upgrade/"$upgradeversion"
FPBX13=`php -r 'if (!@include_once(getenv("FREEPBX_CONF") ? getenv("FREEPBX_CONF") : "/etc/freepbx.conf")) {include_once("/etc/asterisk/freepbx.conf");} echo (version_compare_freepbx(getVersion(),"13.0.0alpha1",">="))?1:0;'`
if [ "$FPBX13" -eq "0" ]; then
amportal a m << QUERY_INPUT
use asterisk;
UPDATE admin SET value = '13.0.0alpha1' WHERE variable = 'version';;
QUERY_INPUT
sudo -u asterisk /var/lib/asterisk/bin/module_admin download framework
sudo -u asterisk /var/lib/asterisk/bin/module_admin install framework
fi

#check to see if the 13 framework was installed
export FPBXVERSION=`php -r "if (!@include_once(getenv('FREEPBX_CONF') ? getenv('FREEPBX_CONF') : '/etc/freepbx.conf')) {include_once('/etc/asterisk/freepbx.conf');} echo getVersion();"`
FPBX13E=`php -r 'if (!@include_once(getenv("FREEPBX_CONF") ? getenv("FREEPBX_CONF") : "/etc/freepbx.conf")) {include_once("/etc/asterisk/freepbx.conf");} echo (version_compare_freepbx(getVersion(),"13.0.0alpha1",">="))?1:0;'`

if [ "$FPBX13" -eq "0" ]; then
       	sudo -u asterisk /var/lib/asterisk/bin/module_admin download framework
       	sudo -u asterisk /var/lib/asterisk/bin/module_admin install framework
       	export FPBXVERSION=`php -r "if (!@include_once(getenv('FREEPBX_CONF') ? getenv('FREEPBX_CONF') : '/etc/freepbx.conf')) {include_once('/etc/asterisk/freepbx.conf');} echo getVersion();"`

       	FPBX13=`php -r 'if (!@include_once(getenv("FREEPBX_CONF") ? getenv("FREEPBX_CONF") : "/etc/freepbx.conf")) {include_once("/etc/asterisk/freepbx.conf");} echo (version_compare_freepbx(getVersion(),"13.0.0alpha1",">="))?1:0;'`
       	if [ "$FPBX13" -eq "0" ]; then
               	echo "An error has occurred updating to FreePBX 13"
               	exit
       	fi
fi
echo " update all FreePBX 13 modules now"
echo " `date` update all FreePBX 13 modules now" >> /var/log/pbx/upgrade/"$upgradeversion"

# Make sure that fwconsole is in /usr/sbin, not /usr/local/sbin
/var/lib/asterisk/bin/freepbx_setting AMPSBIN /usr/sbin
# This will put it there if it's not there.
if [ -e /usr/local/sbin/amportal ]; then
	/usr/local/sbin/amportal a r
elif [ -e /usr/sbin/amportal ]; then
	/usr/sbin/amportal a r
else
	elog "Error: Could not find amportal to complete upgrading to FreePBX 13"
	$SSA --unlock
	exit
fi

if [ ! -e /usr/sbin/fwconsole ]; then
	elog "Error: fwconsole not correctly installed. Please run reload manually"
	$SSA --unlock
	exit
fi

# Now we know fwconsole exists, and is in the right place, we can update
# /etc/rc.local
sed -i 's!^.*bin/amportal!/usr/sbin/fwconsole!g' /etc/rc.local

/usr/sbin/fwconsole --fix_zend
/var/lib/asterisk/bin/freepbx_setting MODULEADMIN_SKIP_CACHE 1
/usr/sbin/fwconsole moduleadmin download backup
/usr/sbin/fwconsole moduleadmin install backup
/usr/sbin/fwconsole moduleadmin download core
/usr/sbin/fwconsole moduleadmin install core
/usr/sbin/fwconsole ma uninstall restart
/usr/sbin/fwconsole ma remove restart
/usr/sbin/fwconsole moduleadmin updateall
/usr/sbin/fwconsole moduleadmin installall
/usr/sbin/fwconsole moduleadmin installall
/usr/sbin/fwconsole chown
/usr/sbin/fwconsole reload
/usr/sbin/fwconsole moduleadmin -R commercial installall
/usr/sbin/fwconsole moduleadmin -R commercial installall
/usr/sbin/fwconsole chown
/usr/sbin/fwconsole reload
###########################################################################
echo
echo "Moving to Next Step"
echo
###########################################################################
# FREEPBX-8937 - Update MOTD
echo " Update MOTD"
echo " `date` Update MOTD" >> /var/log/pbx/upgrade/"$upgradeversion"
# Remove rpm
yum -y erase distro-motd-*
# Also remove the hook from /etc/profile
sed -i '/MOTD.py/d' /etc/profile

# This is a base64 encoded shellscript that safely creates/updates the motd.sh in profile.d
MOTD="IyEvYmluL2Jhc2ggLXgKClJVTkFTPWFzdGVyaXNrCgojIEFyZSB3ZSBsb2dnaW5nIGluPwppZiBbICIkUFMxIiBdIDsgdGhlbgoJIyBBcmUgd2Ugcm9vdD8KCWlmIFsgIiQoL3Vzci9iaW4vaWQgLXUpIiA9PSAiMCIgXTsgdGhlbgoJCVNVPSIvYmluL3N1ICRSVU5BUyAtYyIKCWVsc2UKCQlTVT0iIgoJZmkKCSMgRmluZCBmd2NvbnNvbGUKCWlmIFsgLWUgL3Vzci9zYmluL2Z3Y29uc29sZSBdOyB0aGVuCgkJRldDT05TT0xFPSQoL2Jpbi9yZWFkbGluayAvdXNyL3NiaW4vZndjb25zb2xlKQoJZWxpZiBbIC1lIC91c3IvbG9jYWwvc2Jpbi9md2NvbnNvbGUgXTsgdGhlbgoJCUZXQ09OU09MRT0kKC9iaW4vcmVhZGxpbmsgL3Vzci9sb2NhbC9zYmluL2Z3Y29uc29sZSkKCWZpCglpZiBbIC1lICIkRldDT05TT0xFIiBdIDsgdGhlbgoJCVsgIiRTVSIgXSAmJiAkU1UgIiRGV0NPTlNPTEUgbW90ZCIgfHwgJEZXQ09OU09MRSBtb3RkCgllbGlmIFsgLWUgL3Vzci9sb2NhbC9iaW4vbW90ZCBdIDsgdGhlbgoJCSRTVSAvdXNyL2xvY2FsL2Jpbi9tb3RkCgllbHNlCgkJYm9sZD0kKHRwdXQgc21zbykKCQl1bD0kKHRwdXQgc211bCkKCQlldWw9JCh0cHV0IHJtdWwpCgkJbm9ybWFsPSQodHB1dCBzZ3IwKQoJCWVjaG8gLWUgIlxuJHtib2xkfSoqIENSSVRJQ0FMIFNZU1RFTSBFUlJPUiAqKiR7bm9ybWFsfVxuXG5VbmFibGUgdG8gZ2VuZXJhdGUgTU9URC5cblRoZSAke3VsfS91c3Ivc2Jpbi9md2NvbnNvbGUke2V1bH0gZmlsZSBpcyBub3QgYWNjZXNzaWJsZVxuIgoJCWVjaG8gLWUgIllvdSBhcmUgbGlrZWx5IHRvIGV4cGVyaWVuY2Ugc2lnbmlmaWNhbnQgc3lzdGVtIGlzc3Vlcy5cbiIKCWZpCmZpCg=="
echo $MOTD | base64 -d > /etc/profile.d/motd.sh
chmod 755 /etc/profile.d/motd.sh

###########################################################################
echo
echo "Moving to Next Step"
echo
###########################################################################
echo
echo "STAGE 3 COMPLETED - Misc Items - Moving to Stage 4"
echo "`date` STAGE 3 COMPLETED - Misc Items - Moving to Stage 4" >> /var/log/pbx/upgrade/"$upgradeversion"
echo "" >> /var/log/pbx/upgrade/"$upgradeversion"
echo
$SSA -s -v$upgradeversion -i350
######################### STAGE 3 COMPLETED - MISC ITEMS ##################
echo
echo
######################### STAGE 4 STARTING - CLEAN UP #####################
# Start Stage 4
echo
echo "STAGE 4 STARTING - Clean Up"
echo "`date` STAGE 4 STARTING - Clean Up" >> /var/log/pbx/upgrade/"$upgradeversion"
echo
$SSA -s -v$upgradeversion -i360
###########################################################################
echo " updatedb for locate command"
echo " `date` updatedb for locate command" >> /var/log/pbx/upgrade/"$upgradeversion"
updatedb
echo
###########################################################################
echo " Restart incron to be safe"
echo " `date` Restart incron to be safe" >> /var/log/pbx/upgrade/"$upgradeversion"
/etc/init.d/incrond restart  > /dev/null 2>&1
echo
###########################################################################
# End Stage 4
echo
echo "STAGE 4 COMPLETED - Clean Up - Moving to Stage 5"
echo "`date` STAGE 4 COMPLETED - Clean Up - Moving to Stage 5" >> /var/log/pbx/upgrade/"$upgradeversion"
echo "" >> /var/log/pbx/upgrade/"$upgradeversion"
echo
$SSA -s -v$upgradeversion -i370
############################# STAGE 4 COMPLETED - CLEAN UP ################
echo
echo
################### STAGE 5 STARTING - FINAL VERIFICATIONS ################
# Start Stage 5
echo
echo "STAGE 5 STARTING - Final Verifications"
echo "`date` STAGE 5 STARTING - Final Verifications" >> /var/log/pbx/upgrade/"$upgradeversion"
echo
$SSA -s -v$upgradeversion -i380
###########################################################################
# End Stage 5
echo
echo "STAGE 5 COMPLETED - Final Verifications - Moving to Stage 6"
echo "`date` STAGE 5 COMPLETED - Final Verifications - Moving to Stage 6" >> /var/log/pbx/upgrade/"$upgradeversion"
echo "" >> /var/log/pbx/upgrade/"$upgradeversion"
echo
$SSA -s -v$upgradeversion -i390
################### STAGE 5 COMPLETED - FINAL VERIFICATION ################
echo
echo
################## STAGE 6 STARTING - UPDATE VERSION ######################
$SSA -s -v$upgradeversion -i400
# Update version number now and close out logs and update script
echo "$upgradeversion" > /etc/schmooze/pbx-version
echo "`date` UPGRADE 100% COMPLETED" >> /var/log/pbx/upgrade/"$upgradeversion"
echo "`date` UPGRADE 100% COMPLETED"
$SSA -s -v$upgradeversion -i410
$SSA -s -v$upgradeversion -i800
$SSA -unlock
echo "REBOOT YOUR BOX NOW"
echo "If you would like to change your Asterisk release version from"
echo "1.8, 10, 11 or 12 you can do so by typing asterisk-version-switch"
echo "from the linux CLI at anytime"
echo
echo "`date` REBOOT YOUR BOX NOW" >> /var/log/pbx/upgrade/"$upgradeversion"
echo "If you would like to change your Asterisk release version from 11 or 13 you can do so by typing asterisk-version-switch" >> /var/log/pbx/upgrade/"$upgradeversion"
echo "from the linux CLI at anytime" >> /var/log/pbx/upgrade/"$upgradeversion"
exit
################################################# STAGE 6 COMPLETED - UPDATE VERSION #####################################################
