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

# This script installs or update VoipNow 3 on supported OS

# Version of installer
ver='4.1.3'

# Version file
vfile='/usr/local/voipnow/.version'

# Download site
dsite='http://download2.4psa.com/voipnow/release-4.0.0'

get_install_type() {
	if [ -f ${vfile} ];then
		echo 3
	else
		if [[ -n "$ALT_DB_HOST" && -n "$ALT_DB_PORT" && -n "$ALT_DB_USER" && -n "$ALT_DB_PASSWD" && -n "$ALT_DB_NAME" ]]; then
			echo 2
		elif [ -n "$VNSTANDBY" ]; then
			echo 4;
		elif [ "${this_is_mysql}" -eq 1 ]; then
			echo 5;
		else
			echo 1
		fi
	fi
}

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
	echo "ERROR: $*"
	echo
	echo "Check the error reason, fix and try again."
	echo "You are welcome to open a support ticket at https://help.4psa.com!"
	echo
	rm -f ${repolocal} local$$
	rm -f /var/lock/subsys/vninstaller
	exit 1
}


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 
		curl -L http://www.4psa.com/software/4PSA-GPG-KEY -o 4PSA-GPG-KEY 2> /dev/null
		rpm --import 4PSA-GPG-KEY
		if [ $? -eq 0 ];then
			echo "OK"
		else
			die "Could not import 4PSA signature. RPM package cannot be checked without it!"
		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_deps()
{
	which yum >/dev/null 2>&1
	if [ $? -gt 0 ];then
		echo "yum binary can not be found."
		die "It's not in the system PATH or in a standard location."
	fi
	
	which ifconfig >/dev/null 2>&1
    if [ $? -gt 0 ];then
		yum -y install net-tools >/dev/null 2>&1
		if [ $? -gt 0 ];then	
			echo "ifconfig binary can not be found and package net-tools could not be installed."
			die "It's not in the system PATH or in a standard location."
		fi
	fi
}


check_dahdi()
{
	if [ "${virtuozzo}" != 1 -a "${this_is_dahdi}" = 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 "STRONGLY 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 /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
}

trap log_trap 1 2 15


get_dahdi()
{
	echo
	echo "==> Add Dahdi Linux drivers..."
	yum ${step} -c ${yumconf} 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 ${step} -c ${yumconf} update dkms dahdi-linux-dkms dahdi-linux dahdi-tools gcc make kernel-devel
}


remove_conflicts()
{
	if [ ! -f ${vfile} ];then
		echo "==> Trying to remove software packages that conflict with ${product_name}..."
		#try to stop apache anyway
		service httpd stop >/dev/null 2>&1
		
		yum ${step} -c ${yumconf} install MariaDB-shared-compat postfix >/dev/null 2>&1
		yum ${step} -c ${yumconf} remove spandsp sox asterisk asterisk-sounds asterisk-addons httpd apache apache2 sendmail mysql speex ghostscript libyaml >/dev/null 2>&1
		
		showfinalnotice=1
	else
		echo "==> Update postfix to address any dependency issues..."
		yum ${step} -c ${yumconf} install MariaDB-shared-compat postfix >/dev/null 2>&1
		local version=`cat ${vfile} | awk '{print $1}' -| awk -F'.' '{print $1$2$3}'`
		echo
		if [ "${version}" -lt 300 ];then
			echo
			echo "==> Cleaning up repositories..."
			yum ${step} -c ${yumconf} clean all
			echo
			echo "==> Remove pre 3.0.0 ${product_name} 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 >/dev/null 2>&1
			done
			echo
		fi
		if [ "${version}" -lt 350 ];then
			echo
			echo "==> Remove pre 3.5.0 ${product_name} packages..."
			local rmpacklist="librabbitmq-c"
			for remove_package in ${rmpacklist};do
				echo -n "..."
				rpm -e ${remove_package} --nodeps >/dev/null 2>&1
			done

			rpm -q voipnow-asterisk-codec-g729 >/dev/null
			if [ $? -eq 0 ];then
				echo -n "..."
				vac_installed=1
				rpm -e voipnow-asterisk-codec-g729 --nodeps >/dev/null 2>&1
			fi
			echo
		fi
		showfinalnotice=0
	fi
}


update_os()
{
	echo
	echo "==> Updating Operating System packages (other than ${product_name})..."
	yum ${step} -c ${yumconf} update ${disablevoipnow} --exclude=jansson --exclude=libgphoto2
	if [ $? -gt 0 ];then
		die "Could not upgrade Operating System!"
	fi
	echo
}


welcome() {

	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
	echo -ne	"You are about to ${action}"
	echo
	echo
	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()
{
	if [ -f /etc/redhat-release ];then
		rhel=`grep "^Red Hat Enterprise Linux" /etc/redhat-release`
		centos=`grep "^CentOS" /etc/redhat-release`
		
		release=`cat /etc/redhat-release | cut -d'.' -f1 | awk '{print $NF}'`
		
		if [ ! -z "${rhel}" ];then
			sys="rhel"
		fi

		if [ ! -z "${centos}" ];then
			sys="rhel"
		fi
	fi

	if [ -z "${sys}" -o -z "${release}" ];then
		echo "Can not determine Linux distribution."
		exit 127
	fi
			
	if [ -f /proc/vz/veinfo ];then
	# we are under Virtuozzo
		virtuozzo=1
	else
		virtuozzo=0
	fi
	
	if [ "${VNDEBUG}" ];then
		debugrpm='--rpmverbosity=debug'
	else
		debugrpm=''
	fi
}


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


remove_voipnow()
{
	if [ ! -f ${vfile} ];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 lose 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
	case "${answer}" in
		AGREE)
			yum ${step} -c ${yumconf} remove voipnow-admin-php voipnow-sox voipnow-asterisk-extra voipnow-asterisk-addons voipnow-webmanagement voipnow-automation voipnow-worker voipnow-admin voipnow-asterisk voipnow-asterisk-sounds voipnow-core dahdi-tools dahdi-linux-dkms dahdi-linux hubring libhubring httpsa-admin httpsa-admin-php voipnow-ejabberd voipnow-spandsp hwcelery elasticsearch
			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
}


install_with_yum()
{
	echo
	echo "==> Starting ${product_name} ${action1} procedure."
	echo "This process will take a while..."
	echo
	
	upgradeok=-1
	installok=-1
	
	yum ${step} -c ${yumconf} clean metadata >/dev/null 2>&1
	echo
	
	if [ "${action1}" = "upgrade" ];then
		echo "==> Updating MySQL server and dependencies..."
		
		if [ "${ALT_DB_USER}" -a "${ALT_DB_PASSWD}" -a "${ALT_DB_PORT}" -a "${ALT_DB_HOST}" ];then
			local DB_USER=${ALT_DB_USER}
			local DB_PASSWD=${ALT_DB_PASSWD}
			local DB_PORT=${ALT_DB_PORT}
			local DB_HOST=${ALT_DB_HOST}
		else
			if [ -f /etc/voipnow/.sqldb ]; then
				local DB_USER=`grep "^main" /etc/voipnow/.sqldb | cut -d: -f2`
				local DB_PASSWD=`grep "^main" /etc/voipnow/.sqldb | cut -d: -f3`
				local DB_HOST=`grep "^DB_MASTER\>" /etc/voipnow/sqldbase.conf | awk '{print $2}' | grep "^main" | cut -d: -f2`
				local DB_PORT=`grep "^DB_MASTER\>" /etc/voipnow/sqldbase.conf | awk '{print $2}' | grep "^main" | cut -d: -f3`
			fi		
		fi
		
		if [ "${DB_USER}" -a "${DB_PASSWD}" -a "${DB_PORT}" ];then
			mysql -h${DB_HOST} -P${DB_PORT} -u${DB_USER} -p${DB_PASSWD} -e"SHOW VARIABLES LIKE '%version%';" | grep -i "10.0" | grep -i "mariadb" >/dev/null 2>&1
			if [ $? -gt 0 ];then
				my_upgrade=1
			fi
		fi
	
		yum ${debugrpm} ${step} -c ${yumconf} update MariaDB-server MariaDB-client MariaDB-shared
		
		if [ $? -gt 0 ];then
			die "Could not complete MySQL and dependencies upgrade!"
		else
			if [ ${my_upgrade} -eq 1 ];then
				mysql_upgrade -h${DB_HOST} -P${DB_PORT} -u${DB_USER} -p${DB_PASSWD} >/dev/null 2>&1
				service mysql restart
			fi
		fi
		
		# Fix problems with voicemail
		for voicefile in `find  /var/spool/asterisk/voicemail -name 'Old' -type l -exec ls -l {} \; | awk '{print $9}'`;do
			if [ -h ${voicefile} ];then
				unlink ${voicefile} >/dev/null 2>&1
			fi
		done
		
		echo
		echo "===> Updating ${product_name} base components..."
		yum ${debugrpm} ${step} -c ${yumconf} upgrade
		if [ $? -eq 0 ];then
			upgradeok=1
		else
			upgradeok=0
		fi
		yum ${debugrpm} ${step} -c ${yumconf} install voipnow-worker voipnow-core
		
		if [ ${vac_installed} -eq 1 ];then
			yum ${debugrpm} ${step} -c ${yumconf} install voipnow-asterisk-codec-g729
		fi
	else
		echo "==> Entering Phase 2: Performing ${product_name} ${action1}..."
		echo	

		yum ${debugrpm} ${step} -c ${yumconf} install voipnow-automation voipnow-worker voipnow-core
		
		if [ ${vac_installed} -eq 1 ];then
			yum ${debugrpm} ${step} -c ${yumconf} install voipnow-asterisk-codec-g729
		fi
		
		if [ $? -eq 0 ];then
			installok=1
		else
			installok=0
		fi
	fi
	
	# workaround for mysql
	/sbin/chkconfig --add mysql 2>/dev/null || :

	if [ ${installok} -eq 1 -o ${upgradeok} -eq 1 ];then		
		echo
		echo "${product_name} ${action1} completed successfully!"
		if [ ${showfinalnotice} -eq 1 -a -z "${VNSTANDBY}" ];then
			local localip=`/sbin/ifconfig | grep -v "127.0.0.1" | grep -v "inet6" | grep -i "inet" | head -1 | awk '/inet/{print $2}' | cut -d: -f2 | awk '{print $1}'`
			echo
			echo "------IMPORTANT---------"
			echo
			echo "Point your browser to VoipNow Web ManageMent Interface at https://${localip}"
			echo
			echo "Username: admin"
			echo "Password: welcome"
			echo
			echo "Please LOGIN immediately and CHANGE the password."
			echo
			echo "------IMPORTANT---------"
		fi
	else
		echo
		if [ ! -z "${rhel}" ];then
			echo
			echo "IMPORTANT NOTE:"
			echo "Red Hat Enterprise Linux by default does not enable the [rhel-6-server-optional-rpms] repository."
			echo "Edit the file /etc/yum.repos.d/redhat.repo and enable it by changing the 'enabled' option to 1"
			echo
		fi
		die "Could not perform ${product_name} ${action1}!"
	fi
}


pre_selinux()
{
    if [ -f /etc/selinux/config ];then
        echo 
        grep -w "^SELINUX" /etc/selinux/config | grep "disabled" >/dev/null 2>&1
        if [ $? -eq 0 ];then
            echo 
            echo "WARNING: You have to reboot the server in order for new selinux policy to take effect!"
            echo
		fi
	fi
}

post_selinux()
{
    if [ -f /etc/selinux/config ];then
        echo 
		
        grep -w "SELINUX" /etc/selinux/config | grep "disabled\|enforcing" >/dev/null 2>&1
        if [ $? -eq 0 ];then
            echo "==> Switching selinux to Permissive mode..."
		    sed "s#^SELINUX=.*\$#SELINUX=permissive#" /etc/selinux/config > /etc/selinux/selinux.tmp
		    cp -f /etc/selinux/selinux.tmp /etc/selinux/config && rm -f /etc/selinux/selinux.tmp
			echo
		fi
		
        grep -w "SELINUXTYPE" /etc/selinux/config | grep "minimum\|mls" >/dev/null 2>&1
        if [ $? -eq 0 ];then
            echo "==> Switching selinux type to Targeted..."
            sed "s#^SELINUXTYPE=.*\$#SELINUXTYPE=targeted#" /etc/selinux/config > /etc/selinux/selinux.tmp
            cp -f /etc/selinux/selinux.tmp /etc/selinux/config && rm -f /etc/selinux/selinux.tmp
			echo
        fi
		
		/usr/sbin/setenforce 0 >/dev/null 2>&1
	fi
}

check_lockfile()
{
	which lockfile >/dev/null 2>&1
	if [ $? -gt 0 ];then
		# let's install lockfile
		echo "==> Installing required packages..."
		yum -y install procmail >/dev/null 2>&1
		if [ $? -gt 0 ];then
			die "Could not install all pre-required packages!"		
		fi		
	fi
}


check_log()
{
	touch /var/log/voipnow-update.log >/dev/null 2>&1
	chown voipnow:voipnow /var/log/voipnow-update.log >/dev/null 2>&1
}


check_av_updates()
{
	if [ -f ${vfile} ]; then
		no_updates=`yum -q -c ${yumconf} --disablerepo=base --disablerepo=updates check-update | egrep "${grepvoipnowrepo}" | grep -v "\-devel" | grep -v "\-debuginfo" | sed '/^$/d' | wc -l`
		if [ -z "${no_updates}" ];then
			no_updates=0
		fi
	fi
}


get_yumconf()
{
	local repo=''
	curl --connect-timeout 20 -L ${origin} -o ${repolocal} >/dev/null 2>&1
	if [ ! -f ${repolocal} ];then
		die "Could not download from origin: ${origin}"
	fi
	
	# delete old config file
	if [ -f ${yumconf} ];then
		grep -i "mariadb" ${yumconf} >/dev/null 2>&1
		if [ $? -eq 0 ];then
			rm -f ${yumconf} >/dev/null 2>&1
		fi
	fi
	
	local newsign=`md5sum ${repolocal} | awk '{print $1}' 2>/dev/null`
	
	if [ -f ${yumconf} ];then
		local oldsign=`grep "^#sign=" ${yumconf} | cut -d"=" -f2`
	fi
	
	if [ ! -z ${oldsign} ];then
		if [ "${oldsign}" = "${newsign}" ];then
			
			local localrepos=`grep "^\[" ${yumconf} | grep -v "\[main\]" | cut -d "[" -f 2 | cut -d "]" -f1 | grep -w "base" | grep -w "updates"`
				
			for localrepo in ${localrepos};do
				disablevoipnow="${disablevoipnow} --disablerepo=${localrepo}"
			done
		
			return 0
		fi	
	fi
	
	local alldeps=`grep "^http" ${repolocal}`
	
	if [ -z "${alldeps}" ];then
		die "Repository file downloaded from ${origin} is invalid!"
	fi
	
	if [ -f ${yumconf} ];then
		mv -f ${yumconf} ${yumconf}.old
	fi
	
	echo "[main]" > ${yumconf}
	echo "cachedir=/var/cache/voipnow" >> ${yumconf}
	echo "keepcache=0" >> ${yumconf}
	echo "debuglevel=2" >> ${yumconf}
	echo "logfile=/var/log/voipnow-update.log" >> ${yumconf}
	echo "diskspacecheck=1" >> ${yumconf}
	echo "exactarch=1" >> ${yumconf}
	echo "obsoletes=1" >> ${yumconf}
	echo "metadata_expire=300" >> ${yumconf}
	echo "installonly_limit=3" >> ${yumconf}
	echo "reposdir=./" >> ${yumconf}
	echo "exclude=hwphp, hwgdb" >> ${yumconf}
	echo "plugins=1" >> ${yumconf}
	# This is for redhat
	if [ ! -z "${rhel}" ];then
		echo "include=/etc/yum.repos.d/redhat.repo" >> ${yumconf}
	fi
	
	echo >> ${yumconf}
	
	for repo in ${alldeps};do
		curl --connect-timeout 20 -L ${repo} -o local$$ >/dev/null 2>&1
		if [ $? -eq 0 -a -f local$$ ];then
			local localrepo=`grep "^\[" local$$ | cut -d "[" -f 2 | cut -d "]" -f1`
			voipnowrepo="${voipnowrepo} ${localrepo}"
			if [ -z "${grepvoipnowrepo}" ];then
				grepvoipnowrepo="${localrepo}"
			else
				grepvoipnowrepo="${grepvoipnowrepo} \| ${localrepo}"
			fi
			
			disablevoipnow="${disablevoipnow} --disablerepo=${localrepo}"
			
			cat local$$ >> ${yumconf}
			echo >> ${yumconf}
			rm -f local$$
		else
			die "Could not download from origin repo: ${repo}"
		fi
	done
	
	# This is for centos
	if [ ! -z "${centos}" ];then
	
		# Add OS repositories
		echo "[base]" >> ${yumconf}
		echo "name=CentOS-\$releasever - Base" >> ${yumconf}
		echo "mirrorlist=http://mirrorlist.centos.org/?release=\$releasever&arch=\$basearch&repo=os" >> ${yumconf}
		echo "#baseurl=http://mirror.centos.org/centos/\$releasever/os/\$basearch/" >> ${yumconf}
		echo "gpgcheck=1" >> ${yumconf}
		echo "gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-${release}" >> ${yumconf}
		echo >> ${yumconf}

		echo "[updates]" >> ${yumconf}
		echo "name=CentOS-\$releasever - Updates" >> ${yumconf}
		echo "mirrorlist=http://mirrorlist.centos.org/?release=\$releasever&arch=\$basearch&repo=updates" >> ${yumconf}
		echo "#baseurl=http://mirror.centos.org/centos/\$releasever/updates/\$basearch/" >> ${yumconf}
		echo "gpgcheck=1" >> ${yumconf}
		echo "gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-${release}" >> ${yumconf}
		echo >> ${yumconf}
		
	fi
	
	echo "#sign=${newsign}" >> ${yumconf}
	
	return 0
}

install_mysql()
{
	echo
	echo "==> Starting ${product_name} procedure."
	echo "This process will take a while ..."
	echo

	yum ${step} -c ${yumconf} install MariaDB-server MariaDB-client MariaDB-shared tzdata voipnow-nodeconfig
	
	which mysql > /dev/null 2>&1
	
	if [ $? -eq 0 ];then
		mkdir /etc/voipnow > /dev/null 2>&1
		touch /etc/voipnow/.mysql > /dev/null 2>&1
	else
		die "MySQL was not installed. Unknown error."
	fi
}

mysql_setup()
{
	if [ "${this_is_slave}" -eq 0 ];then
		if [ -f voipnowcredentials.conf ];then
			exit 0
		fi

		local findvalue=`mysql -u root mysql -N -e"SELECT Name FROM time_zone_name WHERE Name='utc'" | head -1`

		if [ -z "${findvalue}" ];then
			echo
			echo "==> Importing timezone information to MySQL ..."
			mysql_tzinfo_to_sql /usr/share/zoneinfo 2> /dev/null | mysql -uroot mysql  > /dev/null 2>&1
		fi

		dbpass=`/bin/dd if=/dev/urandom count=1 2>/dev/null | md5sum | cut -b1-10`;
		dbuser=`/bin/dd if=/dev/urandom count=1 2>/dev/null | md5sum | cut -b1-10`;
		if [ -z "${dbpass}" -o -z "${dbuser}" ];then
			echo "Could not generate default MySQL username and password!"
			die "To avoid an incorrect installation on Infrastructure Controller node, setup will exit."
		fi

		DB_USER=${dbuser}
		DB_PASSWD=${dbpass}
		DB_NAME=voipnow
		DB_PORT=3306

		echo "==> Root MySQL credentials generated, configuring local MySQL server!"
		
		mysql --default-character-set=utf8 -uroot -e "UPDATE user set Password=password('${dbpass}'), User='${dbuser}' WHERE User='root';FLUSH PRIVILEGES;" mysql || die "Could not change the root MySQL password!"
		
		echo 'default-storage_engine=InnoDB' >> /etc/my.cnf
		echo 'transaction_isolation=READ-COMMITTED' >> /etc/my.cnf
		echo 'default-time-zone="UTC"' >> /etc/my.cnf
		
		# just to make sure
		
		if [ ${my_upgrade} -eq 1 ];then
			mysql_upgrade -h${ALT_DB_HOST} -P${ALT_DB_PORT} -u${ALT_DB_USER} -p${ALT_DB_PASSWD} >/dev/null 2>&1
			service mysql restart
		fi
	fi
	# stop httpsa service
	/sbin/service httpsa stop 2>/dev/null || :
	/sbin/chkconfig httpsa off 2>/dev/null || :	
}

ask_things()
{
	if [ "${this_is_slave}" -eq 0 ];then
		local suggestip="192.168.1.3"

		if [ -f /etc/voipnow/.mysql ];then
			# we must make sure that credentials are setup
			if [ -z "${ALT_DB_HOST}" -o -z "${ALT_DB_PORT}" -o -z "${ALT_DB_USER}" -o -z "${ALT_DB_PASSWD}" ];then
				echo "MySQL should be upgraded!"
				echo "In order to perform the upgrade it is necessary to export the variables:"
				echo
				echo "ALT_DB_HOST, ALT_DB_PORT, ALT_DB_USER and ALT_DB_PASSWD"
				echo
				echo "Export these variables and try again!"
				exit 1
			fi

			# determine the mysql version
			mysql -h${ALT_DB_HOST} -P${ALT_DB_PORT} -u${ALT_DB_USER} -p${ALT_DB_PASSWD} -e"SHOW VARIABLES LIKE '%version%';" | grep -i "10." | grep -i "mariadb" >/dev/null 2>&1
			
			if [ $? -gt 0 ];then
				my_upgrade=1
			fi
		fi
				
		local localip=`/sbin/ifconfig | grep -v "127.0.0.1" | grep -v "inet6" | grep -i "inet" | head -1 | awk -F: '{print $2}' | awk '{print $1}'`

		if [ ! -z "${localip}" ];then
			suggestip=${localip}
		fi
		
		
		local counter=1
		while [[ ${counter} -le 5 ]]; do
			echo
			echo -n "Specify the local MySQL IP address, this needs to be accessible from the Infrastructure Controller (e.g : ${suggestip}): "
			
			read dbhost
			ifconfig -a | grep ${dbhost} >/dev/null 2>&1
			if [ $? -eq 0 ];then
			   counter=5
			else
			   echo 
			   echo -n "${dbhost} is not present on the interfaces on this server. "
			   if [ ${counter} -eq 4 ];then
					die "Exiting ..."
			   else
					echo "Please try another IP."
			   fi
			fi
			(( counter++ ))
		done

		DB_HOST=${dbhost}
	fi
}

save_settings()
{
	if [ "${this_is_slave}" -eq 0 ];then
		if [ -f voipnowcredentials.conf ];then
			return 0
		fi

		mysql --default-character-set=utf8 -u${DB_USER} -p${DB_PASSWD} -e "GRANT ALL PRIVILEGES ON *.* TO '${DB_USER}'@'%' identified by '${DB_PASSWD}' WITH GRANT OPTION;FLUSH PRIVILEGES;" mysql || die "Could not grant access!"

		echo "export ALT_DB_HOST=${DB_HOST}" > voipnowcredentials.conf
		echo "export ALT_DB_PORT=3306" >> voipnowcredentials.conf
		echo "export ALT_DB_USER=${DB_USER}" >> voipnowcredentials.conf
		echo "export ALT_DB_PASSWD=${DB_PASSWD}" >> voipnowcredentials.conf
		echo "export ALT_DB_NAME=voipnow" >> voipnowcredentials.conf
		
		echo
		echo    "Root MySQL credentials were saved in voipnowcredentials.conf"
		echo    "Installation procedure completed succesfully!"
		echo
	fi
}

origin_find()
{
	# Determine installer course
	if [ ! -z "${VOIPNOW_REPO}" ];then
		origin=${VOIPNOW_REPO}/${sys}${release}/repo-internal.dep
	else
		origin=${dsite}/${sys}${release}/repo.dep
	fi
}

determine_op()
{
	local x=$(get_install_type)
	case "${x}" in
		1)
			action="install the first VoipNow node in your infrastructure.\nAll components will be installed on this node."
			action1="installation"
		;;
		2)	
			action="install the first VoipNow node in your infrastructure\nConnected to MySQL node hostname:${ALT_DB_PORT}, username: ${ALT_DB_USER}, password: ${ALT_DB_PASSWD}, database: ${ALT_DB_NAME}"
			action1="installation"
		;;
		3)
			action="upgrade this VoipNow node.\nThere are ${no_updates} packages for upgrade.\n\nPlease read the Release Notes before upgrading!"
			action1="upgrade"
		;;
		4)
			action="install a standby VoipNow node that will join a VoipNow infrastructure.\n\nPlease read http://wiki.4psa.com/display/VNINST30/Distributed+System+Deployment before continuing"
			action1="installation"
		;;
		5)
			action="install a MySQL node for VoipNow.\n\nPlease read http://wiki.4psa.com/display/VNINST30/Distributed+System+Deployment before continuing"
			action1="installation"
		;;
	esac
}

log_trap()
{
	die "FAIL: Abnormal kill detected!"
}

# main
cd `dirname $0`
product_name='VoipNow (R)'
config_voipnow_old="/etc/voipnow/voipnow.conf"
repolocal=repo.dep$$
yumconf="/etc/voipnow-yum.conf"
voipnowrepo=''
grepvoipnowrepo=''
disablevoipnow=''
step='-y'
this_is_mysql=0
this_is_dahdi=0
this_is_slave=0
vac_installed=0

is_root
auto=0
check=0
my_upgrade=0

# This is automode
if [ "$1" = "auto" ];then
    auto=1
fi

# This is check
if [ "$1" = "check" ];then
    check=1
fi

# This is mysql installation
if [ "$1" = "mysql" ];then
	this_is_mysql=1
	if [ "$2" = "slave" ];then
		this_is_slave=1
	fi
fi

if [ "$1" = "dahdi" ];then
	this_is_dahdi=1
fi

# Necessary until sysctl is modified
ulimit -n 32768

# This is installation
check_os
check_deps
origin_find
get_yumconf
check_av_updates
	
if [ "${check}" = "1" ];then
	rm -f ${repolocal} local$$
	exit ${no_updates}
fi

determine_op

if [ "${auto}" = "0" ];then
	welcome
fi

pre_selinux
check_lockfile
	
# This is the critical region
lockfile -r 10 /var/lock/subsys/vninstaller
import_4psa_key
import_gpg_keys
remove_conflicts
update_os
if [ "${this_is_mysql}" -eq 0 ];then
	# normal installation
	check_dahdi
	install_with_yum
else
	# mysql installation
	ask_things
	install_mysql
	mysql_setup
	save_settings
fi

post_selinux
check_log
rm -f /var/lock/subsys/vninstaller
	
exit 0
