#!/bin/sh
# Copyright (c) 2002-2012 by 4PSA
# All rights reserved

# This script installs or update VoipNow 3 on supported operating systems

# Modified: $DateTime$
# Revision: $Revision$ with $Change$

# You can modify this to your own mirror of http://voipnow.4psa.com/downloads
repository='http://voipnow.4psa.com/downloads'

# Version of installer
ver='3.0.2'

is_root()
{
current_user="`id`"
case "$current_user" in
	uid=0\(root\)*)
	;;
	*)
		echo "$0: You must have root privileges in order to install ${product_name}"
		echo "Su as root and try again"
		echo
		exit 1
	;;
esac
}


die()
{
	echo "ERROR: $*"
	echo "Check the error reason, fix and try again"
	echo 
	exit 1
}


download_yuminf()
{
	rm -f yum3.inf
	${wget_path}wget -T20 ${repository}/yum3.inf >/dev/null 2>&1
	if [ -f yum3.inf ];then
		yum_location=`grep "^${sys}${release}" yum3.inf | grep "${arch}" | awk '{print $2}'`
		yumconf_location=`grep "^${sys}${release}" yum3.inf | grep "${arch}" | awk '{print $3}'`
		if [ -z ${yum_location} -o -z ${yumconf_location} ];then
			echo
			die "The remote repository does not contain information for this OS!"
		fi
	else
		die "Could not get the yum information file."
	fi
}

download_yum()
{
echo -n "==> Installing yum package manager, please stand-by... "

	download_yuminf
	
	${wget_path}wget -T20 ${repository}${yum_location} >/dev/null 2>&1
	if [ -f `basename ${yum_location}` ];then
		rpm -Uv `basename ${yum_location}`
		if [ $? -eq 0 ];then
			echo 'Done!'
		else
			echo
			echo "Could not install yum RPM package." 
			die "Please solve the dependencies manually and re-execute installer."
		fi
	else
		die "Could not get yum RPM package."
	fi
}


import_4psa_key()
{
	local imported_keys=`rpm -qi gpg-pubkey-* | grep "Rack-Soft, Inc" | wc -l`
	
	if [ "${imported_keys}" -eq 0 ];then
		echo -n "Importing 4PSA RPM key ... "
		rm -f 4PSA-GPG-KEY 
		${wget_path}wget http://www.4psa.com/software/4PSA-GPG-KEY 2> /dev/null
		rpm --import 4PSA-GPG-KEY
		if [ $? -eq 0 ];then
			echo "OK"
		else
			echo "Failed, setup will continue!"
		fi
	fi
}

voipnow2_upgrade()
{
MYSQL51UPGRADE=0
local rmpacklist="MySQL-server-standard MySQL-client-standard perl-DBD-MySQL mysql5-python voipnow-astmanproxy zaptel kernel-module-zaptel kernel-smp-module-zaptel sendmail voipnow-admin voipnow2-admin voipnow-asterisk-addons perl-DBD-MySQL51 mysql51-python 4psa-redis libredis voipnowcallapid"

	if [ ! -z "${MYSQL_SERVER}" ];then
		if [ "${MYSQL_SERVER}" -lt 51 ] && [ -f /usr/local/voipnow/.version ]; then
			# have to check if the upgrade is for VoipNow 3
			get_variables
			NEWVOIPNOW=`yum -c voipnow-yum.conf check-update | grep -w voipnow | grep -v "debug" | grep "^voipnow-core" | awk '{ print $(NF-1) }' | cut -d- -f1 | awk -F'.' '{print $1$2$3}'`
			if [ ! -z "${NEWVOIPNOW}" ];then
				if [ "${NEWVOIPNOW}" -gt 199 ];then
				echo -n "==> Making a database backup just to be safe ... "
				current_date=`date +%k_%M_%S_%d_%m_%Y`
				if [ ! -d ${DUMPS_D} ];then
					mkdir -p ${DUMPS_D}
				fi
				mysqldump --single-transaction --quick --quote-names --extended-insert --routines --triggers -h${DB_HOST} -u${DB_USER} -p${DB_PASSWD} ${DB_NAME} > ${DUMPS_D}/voipnowupgrade${current_date}.sql
				if [ $? -eq 0 ];then
					echo "OK"
				else
					echo "Failed"
					die "Please make sure that you have a database backup before continuing the upgrade procedure"
				fi
				echo -n "==> Installing pre-requirements for VoipNow 2.x upgrade..."
				yum -y -c voipnow-yum.conf install MySQL-shared-compat-standard postfix
				echo -n "==> Having to upgrade MySQL to 5.5, processing..."
					# mysql is old and we upgrade to VoipNow 2
					/etc/init.d/mysql stop
					killall -9 mysqld_safe mysqld 2>/dev/null
					sed '/default-storage_engine/d' /etc/my.cnf | sed '/skip-bdb/d' | sed '/skip-ndbcluster/d' > /etc/my.cnf$$
					mv /etc/my.cnf$$ /etc/my.cnf
					for remove_package in ${rmpacklist};do
						echo -n "..."
						rpm -e ${remove_package} --nodeps 2>/dev/null
						MYSQL51UPGRADE=1
					done
				fi
			else
				echo "Looks like ${product_name} is the latest version, we will check for additional components only!"
			fi
		fi
	fi
}

get_variables()
{
if [ -f ${config_voipnow_old} ];then
		DB_USER=`grep "^DB_USER\>" ${config_voipnow_old} | awk '{print $2}'`
		DB_PASSWD=`grep "^DB_PASSWD\>" ${config_voipnow_old} | awk '{print $2}'`
		DB_HOST=`grep "^DB_HOST\>" ${config_voipnow_old} | awk '{print $2}'`
		DB_NAME=`grep "^DB_NAME\>" ${config_voipnow_old} | awk '{print $2}'`
		DUMPS_D=`grep "^DUMPS_D\>" ${config_voipnow_old} | awk '{print $2}'`
fi
}

check_yum()
{
which yum >/dev/null 2>&1
if [ $? -gt 0 ];then
	# yum is not in path
	rpm -q yum >/dev/null 2>&1
	if [ $? -gt 0 ];then
		#yum must be downloaded and installed
		download_yum
	else
		#yum seems installed, but not in path
		if [ -f /usr/bin/yum ];then
			#yum was found in /usr/bin
			yum_path='/usr/bin/'
		else
			echo "The RPM package manager yum is installed on your system, but ${product_name} installer can not find it."
			die "It's not in the system PATH or in a standard location"
		fi
	fi
fi
}


check_wget()
{
which wget >/dev/null 2>&1
if [ $? -gt 0 ];then
	if [ -f /usr/bin/wget ];then
		wget_path='/usr/bin/'
	else
		echo "wget binary can not be found."
		die "It's not in the system PATH or in a standard location."
	fi
fi
}


get_yumconf()
{
	download_yuminf
	rm -f voipnow-yum.conf
	
	${wget_path}wget -T20 ${repository}${yumconf_location} >/dev/null 2>&1
	if [ ! -f voipnow-yum.conf ];then
		die "Could not get voipnow-yum.conf"
	fi
}

check_dahdi()
{
if [ "${virtuozzo}" != 1 ];then
	#check for dahdi version
	echo "==> Check and remove zaptel if available "
	rpm -qi "zaptel" 1>>/dev/null 2>&1
	if [ $? -eq 0 ];then
		rpm --nodeps zaptel kernel-module-zaptel kernel-smp-module-zaptel 1>>/dev/null 2>&1
	fi
	rpm -qi "dahdi-linux-dkms" 1>>/dev/null 2>&1
	if [ $? -gt 0 ];then
		# must be downloaded or compiled
		if [ ! -f /root/.nodahdi ];then
			ask_dahdi
		fi
	fi
fi
}

ask_dahdi()
{
echo
echo	
echo "Do you want to install drivers for Dahdi interface cards?"
echo
echo "STRONLY NOT RECOMMENDED IF YOU DO NOT HAVE AN INTERFACE CARD."
echo
echo "What do you want to do (No/Yes)? [N] "

read answer

case "${answer}" in
	y*|Y*)
		rm -f touch /root/.nodahdi 2>/dev/null
		get_dahdi
	;;
	*)
		touch /root/.nodahdi
		echo
		echo "If you want to install later Dahdi delete the file /root/.nodahdi"
		echo "and re-execute the installer."
	;;
esac
echo
}

get_dahdi()
{
	echo
	echo "==> Add Dahdi Linux drivers ..."
	yum -y -c voipnow-yum.conf install dkms dahdi-linux-dkms dahdi-linux dahdi-tools gcc make kernel-devel
	echo "==> Install Dahdi updates if any is available ...."
#we need this since install on packet name does not update it, and update does not install if missing
	yum -y -c voipnow-yum.conf update dkms dahdi-linux-dkms dahdi-linux dahdi-tools gcc make kernel-devel
}

remove_conflicts()
{
	if [ ! -f /usr/local/voipnow/.version ];then
		echo
		echo "==> Trying to remove software packages that conflict with VoipNow ..."
		#try to stop apache anyway
		if [ -x "/etc/rc.d/init.d/httpd" ];then
			/etc/rc.d/init.d/httpd stop >/dev/null 2>&1
		fi
		if [ -x "/etc/init.d/httpd" ];then
			/etc/init.d/httpd stop >/dev/null 2>&1
		fi
		if [ -x "/etc/init.d/apache" ];then
			/etc/init.d/apache stop >/dev/null 2>&1
		fi
		if [ -x "/etc/init.d/apache2" ];then
			/etc/init.d/apache2 stop >/dev/null 2>&1
		fi
		yum -y -c voipnow-yum.conf install MySQL-shared-compat-standard postfix
		yum -y -c voipnow-yum.conf remove spandsp sox asterisk asterisk-sounds asterisk-addons httpd apache apache2 sendmail mysql speex ghostscript >/dev/null 2>&1
	else
		echo "==> Update postfix in order to prevent fail due to mysql dependency..."
		yum -y -c voipnow-yum.conf install MySQL-shared-compat-standard postfix
		local version=`cat /usr/local/voipnow/.version | awk '{print $1}' -| awk -F'.' '{print $1$2$3}'`
		if [ "${version}" -lt 300 ];then
			echo
			echo "==> Cleaning up repositories..."
			yum -y -c voipnow-yum.conf clean all
			echo
			echo "==> Remove old VoipNow packages..."
			local rmpacklist="mysql51-python perl-DBD-MySQL51 voipnow-asterisk-addons voipnow2-admin voipnow-admin-php googleperftools voipnowcallapid 4psa-redis voipnow-asterisk-codec-g729"
			for remove_package in ${rmpacklist};do
				echo -n "..."
				rpm -e ${remove_package} --nodeps 2>/dev/null
			done
		fi
	fi
}

update_os()
{
	echo "==> Updating Operating System software ..."
	yum -y -c voipnow-yum.conf update --disablerepo=voipnow --disablerepo=4psaoss
}

welcome() {
if [ -f /usr/local/voipnow/.version ];then
	action="There are ${no_updates} packages for upgrade. Procedure can start immediatly."
	action1="upgrade"
else
	action='Installation procedure can start immediatly.'
	action1="installation"
fi

curdepth=`pwd | wc -c`

if [ "${curdepth}" -lt 4 ];then
	die "Please do not execute this script from system /"
fi

echo
echo	
echo	"${product_name} Command Line Auto-Installer version ${ver}."
echo
echo	"Please read the Release Notes before running this script."
echo
echo
echo	"${action}"
echo
echo	"You will see a lot of messages on the screen, these are NORMAL."
echo 	"Do not stop the installation procedure once started."
echo
echo "Do you want to continue (Yes/No)? [Y] "

read answer

case "${answer}" in
	y*|Y*)
	;;
	*)
		echo
		echo "You will be able to install/update ${product_name} later."
		echo
		exit 1
	;;
esac
echo
}

check_os()
{
config="/etc/psa/psa.conf"
TARGET_OS="`uname -a`"
	case "$TARGET_OS" in
        Linux*[23].?.*?86*|Linux*ppc*)
		
		kernel_flavor=''
		
		uname -r | grep -i "default" > /dev/null
		
		if [ $? -eq 0 ];then
			kernel_flavor='-default'
		fi

		uname -r | grep -i "smp" > /dev/null
		
		if [ $? -eq 0 ];then
			kernel_flavor='-smp'
		fi
				
		if [ -f /etc/SuSE-release ];then
			sys="suse"
			release=`grep "^VERSION" /etc/SuSE-release | cut -d= -f2 | awk '{print $1}'`
		fi
   		if [ -f /etc/redhat-release ];then
			fedora=`grep "^Fedora" /etc/redhat-release`
			rhel=`grep "^Red Hat Enterprise Linux" /etc/redhat-release`
			centos=`grep "^CentOS" /etc/redhat-release`
	
			if [ ! -z "${fedora}" ];then
				sys="fc"
				release=`cat /etc/redhat-release | awk '{print $4}'`
			fi
			if [ ! -z "${rhel}" ];then
				sys="rhel"
				release=`cat /etc/redhat-release | awk '{print $7}' | cut -d'.' -f1`
			fi
			if [ ! -z "${centos}" ];then
				sys="centos"
				release=`cat /etc/redhat-release | awk '{print $3}' | cut -d'.' -f1`
			fi
   		fi
   		if [ -z "${sys}" -o -z "${release}" ];then
   			echo "Can not determine Linux distribution."
   			exit 127
   		fi
   		
		;;
	*)	echo "You do not have a supported OS."
		exit 127
		;;
esac

if [ -z "${sys}" -o -z "${release}" ];then
	echo "You do not have a supported OS."
	exit 127
fi

if [ -f /proc/vz/veinfo ];then
# we are under Virtuozzo
	virtuozzo=1
else
	virtuozzo=0
fi
}

get_arch()
{
	if [ ${sys} = "suse" ];then
		arch='i586'
	else
		arch=`uname -i`
	fi
}



check_repo_cache()
{
get_yumconf
cache_dir=`grep "^cachedir" voipnow-yum.conf | cut -d'=' -f2`
    
if [ ! -d ${cache_dir} ];then
        mkdir -p ${cache_dir}
fi
}

import_gpg_keys()
{
# this is a hack
for gpgkey in `grep "^gpgkey" voipnow-yum.conf | cut -d'=' -f2 | awk '{print $1}'`;do
	rpm --import ${gpgkey} >/dev/null 2>&1
done
}

remove_voipnow()
{

if [ ! -f /usr/local/voipnow/.version ];then
	die "The product must be installed first, and then removed!"
fi
if [ "$auto" = "0" ];then
echo
echo
echo
echo	"ARE YOU SURE THAT YOU WANT TO UNINSTALL ${product_name}?"
echo 
echo	"You will loose EVERYTHING related to ${product_name}"
echo	"and you cannot recover it later. If you are sure, type AGREE (in capitals)"
echo
echo "Do you want to continue? [N] "

read answer
else 
    answer="AGREE"
fi
exit
case "${answer}" in
	AGREE)
		yum -y -c voipnow-yum.conf remove voipnow-admin-php voipnow-sox voipnow-asterisk-extra voipnow-asterisk-addons voipnow-php voipnow-admin voipnow-asterisk voipnow-asterisk-sounds voipnow-core dahdi-tools dahdi-linux-dkms dahdi-linux
		if [ $? -eq 0 ];then
			echo
			die "An error occured while uninstalling ${product_name}."
		else
			echo
			echo "${product_name} uninstalled successfully ."
			exit 0
		fi

	;;
	*)
		echo
		echo "Did you hear the voice? Wise choice."
		echo
		exit 0
	;;
esac
echo
}

check_update()
{
echo
echo "==> Refreshing local repository with latest updates..."
yum -c voipnow-yum.conf check-update
}


install_with_yum()
{
echo
echo "==> Starting ${product_name} ${action1} procedure."
echo "This process will take a while ..."
echo
if [ "${VNDEBUG}" ];then
	yum --rpmverbosity=debug -y -c voipnow-yum.conf groupupdate voipnow libvn3
else
	yum -y -c voipnow-yum.conf groupupdate voipnow libvn3
fi

if [ $? -eq 0 ];then
	if [ ${MYSQL51UPGRADE} -eq 1 ];then
		echo -n "==> Completing upgrade of old database schema to MySQL 5.1 ... "
		mysql_upgrade -u${DB_USER} -p${DB_PASSWD} >/dev/null 2>&1
	fi
	echo
	echo "${product_name} ${action1} completed successfully!"
	exit 0
else
	echo
	echo "Could not install ${product_name}!"
	echo
	echo "If ${product_name} is conflicting with an installed package, uninstall the offending package with:"
	echo "rpm -e package_name"
	echo
	echo "Otherwise please contact support."
	exit 1
fi
}

check_selinux()
{
if [ -f /etc/sysconfig/selinux ];then
	echo 
	echo "==> Switching selinux to Permissive mode ..."
	sed '/SELINUX/s#enforcing#permissive#g' /etc/sysconfig/selinux > /etc/sysconfig/selinux.tmp
	cp -f /etc/sysconfig/selinux.tmp /etc/sysconfig/selinux && rm -f /etc/sysconfig/selinux.tmp
	/usr/sbin/setenforce 0
fi
}

check_av_updates()
{
	if [ -f /usr/local/voipnow/.version ]; then
		no_updates=`yum -c voipnow-yum.conf check-update --disablerepo=base --disablerepo=addons --disablerepo=extras --disablerepo=update | grep " 4psaoss\| voipnow" | wc -l`
		if [ -z "${no_updates}" ];then
			no_updates=0
		fi
	fi
}


# main

cd `dirname $0`
product_name='VoipNow (R)'
yum_path=''
wget_path=''
config_voipnow_old="/etc/voipnow/voipnow.conf"

is_root
auto=0
if [ "$1" = "auto" ];then
    auto=1
fi
if [ "$1" = "remove" ] || [ "$2" = "remove" ];then
	remove_voipnow
else
	check_os
	get_arch
	check_wget
	check_yum
	check_selinux
	if [ "$auto" = "0" ];then
		check_av_updates
		welcome
	fi
	import_4psa_key
	check_repo_cache
	import_gpg_keys
	remove_conflicts
	update_os
	voipnow2_upgrade
	check_update
	check_dahdi
	install_with_yum
fi

exit 0
