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

# This script installs or update VoipNow on supported OS

# Name of the product
product_name='VoipNow (R)'

# Version of installer
installer_ver='5.5.0'

# Version tag
installer_tag='M1'

# Beta installer
beta=0

# Minimum version of MariaDB
mariadb_ver='10.5'

# These packages should be excluded from repositories
exclude_pack='elasticsearch5*,elasticsearch7*'

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

# Root dir for voipnow
voipnowrootd='/usr/local/voipnow'

# Download site
dsite='https://download2.4psa.com/voipnow/latest'

# Log directory
error_log_dir='/root/voipnow'

# Update log file
update_log='/var/log/voipnow-update.log'

# Customize shell
PS1='\[\033[02;32m\]\u@\h:\[\033[02;34m\]\w\$\[\033[00m\] '
RED='\033[0;31m'
GREEN='\033[0;42m'
NC='\033[0m'

# Supported OS code
sys='rhel'

# MySQL credentials file
voipnowcredentials=/etc/voipnow/voipnowcredentials.conf

# More variables
_sysconfdir=/etc

log_general()
{
    # add to log
    echo "`date +'%b %d %H:%M:%S'` $*"  >> ${update_log}
    chown voipnow:voipnow ${update_log} >/dev/null 2>&1
}

prepare_log()
{
    if [ ! -d ${error_log_dir} ];then
        mkdir ${error_log_dir}
    fi
    
    if [ -f ${error_log_dir}/install_error.log ];then
        mod_date=`stat -c %Z ${log_dir}/install_error.log`
        mv ${error_log_dir}/install_error.log ${error_log_dir}/install_error_${mod_date}.log
    fi
}

get_install_type() {
    if [ "${this_is_mysql}" == "1" ]; then
        return 5
    fi
    if [ -d ${voipnowrootd} ];then
        return 3
    fi
    if [ -n "$VNSTANDBY" ]; then
        return 4
    fi
    if [[ -n "$ALT_DB_HOST" && -n "$ALT_DB_PORT" && -n "$ALT_DB_USER" && -n "$ALT_DB_PASSWD" && -n "$ALT_DB_NAME" ]]; then
        return 2
    fi
    
    return 1
}

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
    
    log_general "Stopped: ERROR - $*"
    
    rm -f ${repolocal} local$$
    rm -f /var/lock/subsys/vninstaller
    exit 1
}

ok()
{
    echo "OK!"
    echo
}

import_4psa_key()
{
    local imported_keys=`rpm -qi gpg-pubkey-* | grep "Rack-Soft, Inc" | wc -l`
    
    if [ "${imported_keys}" == "0" ];then
        echo "==> Importing 4PSA RPM key... "
        rm -f 4PSA-GPG-KEY 
        curl -f -L https://www.4psa.com/software/4PSA-GPG-KEY -o 4PSA-GPG-KEY 2> /dev/null
        rpm --import 4PSA-GPG-KEY
        if [ "$?" -eq "0" ];then
            ok
        else
            die "Could not import 4PSA signature. RPM package cannot be checked without it!"
        fi
    fi
}

node_restart()
{
    if [ -f /etc/voipnow/.dirty_node ];then
        echo "==> Restarting node.js engine... "
        service node reload
        rm -f /etc/voipnow/.dirty_node
    fi
}

friendly_wait()
{
    echo
    echo
    echo "Checking system, please wait..."
    echo
}

check_deps()
{
    if [ "${release}" == "6" -o "${release}" == "7" ];then
        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."
        else
            pm="yum"
        fi
    fi
    
    if [ "${release}" == "8" ];then
        which dnf >/dev/null 2>&1
        if [ "$?" -gt "0" ];then
            echo "dnf binary can not be found."
            die "It's not in the system PATH or in a standard location."
        else
            pm="dnf"
        fi
    fi
    
    which ip >/dev/null 2>&1
    if [ "$?" -gt "0" ];then
        ${pm} -y install iproute >/dev/null 2>&1
        if [ "$?" -gt "0" ];then    
            echo "ip binary can not be found and package iproute could not be installed."
            die "It's not in the system PATH or in a standard location."
        fi
    fi
}

trap log_trap 1 2 15

remove_conflicts()
{
    if [ ! -d ${voipnowrootd} ];then
        echo "==> Trying to remove packages that conflict with ${product_name}..."
        #try to stop apache anyway
        service httpd stop >/dev/null 2>&1
        
        ${pm} ${step} -c ${pmconf} install postfix >/dev/null 2>&1
        ${pm} ${step} -c ${pmconf} remove asterisk asterisk-sounds asterisk-addons httpd apache apache2 sendmail mysql >/dev/null 2>&1
        ok
    fi
}

upgrade_es()
{
    [ -f /etc/voipnownode/nodeid ] && nodeid=`cat /etc/voipnownode/nodeid`
        
    if [ -n ${nodeid} ];then
    
        is_ic=`mysql -h${DB_HOST} -P${DB_PORT} -u${DB_USER} -p${DB_PASSWD} ${DB_NAME} -N -e"SELECT count(nodeid) FROM node_role WHERE role='ic' AND nodeid='${nodeid}' AND status=1"`
        if [ "${is_ic}" == "1" ];then
            # is elasticsearch installed?
            rpm -q elasticsearch > /dev/null
            if [ "$?" -eq "0" -a ! -f /etc/voipnow/.es1_uc ];then
                echo
                ${pm} ${step} -c ${pmconf} install elasticsearch-upgrade >/dev/null 2>&1
                if [ -f ${voipnowrootd}/etc/es/upgradees1/migrate-es2.js ];then
                    echo "==> Executing upgrade preparations for ES 2 (this might take a while, DO NOT STOP)..."
                    NODE_PATH=/usr/lib/node_modules node ${voipnowrootd}/etc/es/upgradees1/migrate-es2.js ${voipnowrootd}/etc/es/upgradees1/templates > es1_upgrade_`date | sed 's/ /_/g'`.log
                    if [ "$?" -eq "0" ];then
                        echo `date` > /etc/voipnow/.es1_uc
                        rpm -e elasticsearch --nodeps >/dev/null 2>&1
                        ok
                    else
                        die "Critical, Elasticsearch upgrade failed! Please contact support."
                    fi
                fi
            fi
        fi
    fi
}

check_minver()
{
    if [ -f ${vfileold} ];then
        local version=`cat ${vfileold} | awk '{print $1}' -| awk -F'.' '{print $1$2$3}'`
    fi
    if [ -f ${vfile} ];then
        local version=`cat ${vfile} | awk '{print $1}' -| awk -F'.' '{print $1$2$3}'`
    fi
    if [ -z "${version}" ];then
        return 0
    fi
    
    if [ "${version}" -lt "350" -a "${version}" -gt "0" ];then
        echo
        echo
        echo "You are using an old ${product_name} version and you cannot upgrade to ${product_name} ${installer_ver}${installer_tag} directly."
        die "Please contact 4PSA Help Desk in order to check for your upgrade options!"
    fi
}

detect_version()
{
    if [ "${this_is_mysql}" == "1" ];then
        return 0
    fi

    if [ -f ${vfileold} ];then
        versionf=`cat ${vfileold}`
        version=`echo ${versionf} | awk '{print $1}' -| awk -F'.' '{print $1$2$3}'`
        return 0
    fi
    if [ -f ${vfile} ];then
        versionf=`cat ${vfile}`
        version=`echo ${versionf} | awk '{print $1}' -| awk -F'.' '{print $1$2$3}'`
        return 0
    fi
    
    if [ "${DB_USER}" -a "${DB_PASSWD}" -a "${DB_PORT}" ];then    
        versionf=`mysql -h${DB_HOST} -P${DB_PORT} -u${DB_USER} -p${DB_PASSWD} ${DB_NAME} -N -e"SELECT value FROM misc WHERE param='db_version'"`
        if [ ! -z "${versionf}" ];then
             version=`echo ${versionf} | awk '{print $1}' -| awk -F'.' '{print $1$2$3}'`
             return 0
        fi
    fi
    
    if [ -d ${voipnowrootd} -a -z "${version}" ];then
        die "Could not detect old ${product_name} version, although the software seems installed."
    else
        version=0
        return 1
    fi
}

selinux_cleanup()
{
    # Remove old nodejs port definition
    semanage port -d -t node_port_t -p tcp 40001 >/dev/null 2>&1 || :
    semanage port -d -t node_port_t -p tcp 40002 >/dev/null 2>&1 || :
    semanage port -d -t node_port_t -p tcp 40003 >/dev/null 2>&1 || :

    semodule -l | grep -E "^nodejs|^kamailio|voipnow-asterisk|voipnow-httpsa|voipnow-phpfpm|voipnow-elasticsearch|voipnow-mysql" > /dev/null 2>&1
    if [ "$?" -eq "0" ]; then
        #Remove old selinux modules

        semanage port -d -t elasticsearch_port_t -p tcp 9200 >/dev/null 2>&1 || :
        semanage port -d -t elasticsearch_port_t -p tcp 9300 >/dev/null 2>&1 || :
        
        semanage port -d -t node_port_t -p tcp 17000-17999 >/dev/null 2>&1 || :
        semanage port -d -t voipnow_imm_port_t -p tcp 14000-14999 >/dev/null 2>&1 || :

        if [ "${release}" == "6" ]; then
            semodule -n -r jabberd rabbitmq voipnow-celery voipnow-epmd asterisk phpfpm httpsa nodejs elasticsearch kamailio hubring s3queuegc s3queueupldel voipnow-s3queuegc voipnow-s3queueupldel voipnow-selinux-collect voipnow-asterisk voipnow-collectd voipnow-common voipnow-elasticsearch voipnow-httpsa voipnow-hubring voipnow-kamailio voipnow-mysql voipnow-nodejs voipnow-phpfpm voipnow-s3queue voipnow-ejabberd > /dev/null 2>&1
        elif [ "${release}" == "7" ]; then
            semodule -n -X 100 -r asterisk -X 400 -r jabberd -X 400 -r rabbitmq -X 400 -r voipnow-celery -X 400 voipnow-epmd -X 400 -r phpfpm -X 400 -r httpsa -X 400 -r asterisk -X 400 -r nodejs -X 400 -r elasticsearch -X 400 -r kamailio -X 400 -r hubring -X 400 -r s3queuegc -X 400 -r s3queueupldel -X 400 -r voipnow-s3queuegc -X 400 -r voipnow-s3queueupldel -X 400 -r voipnow-selinux-collectd -X 400 -r voipnow-asterisk -X 400 -r voipnow-collectd -X 400 -r voipnow-common -X 400 -r voipnow-elasticsearch -X 400 -r voipnow-httpsa -X 400 -r voipnow-hubring -X 400 -r voipnow-kamailio -X 400 -r voipnow-mysql -X 400 -r voipnow-nodejs -X 400 -r voipnow-phpfpm -X 400 -r voipnow-s3queue -X 400 -r voipnow-ejabberd  > /dev/null 2>&1
        fi

        rpm -e voipnow-selinux --nodeps --noscripts > /dev/null 2>&1
        /sbin/load_policy
    fi
}

upgrade_old()
{
    if [ "${this_is_mysql}" == "1" ];then
        return 0
    fi
                    
    if [ "${version}" -lt "411" -a "${version}" -gt "0" ];then
        # check for old libunwind
        rpm -qa | grep "libunwind" | grep "rhel7.x86_64" >/dev/null 2>&1
        if [ "$?" -eq "0" ];then
            rpm -e libunwind --nodeps >/dev/null 2>&1
        fi
    fi
        
        
    if [ "${version}" -lt "525" -a "${version}" -gt "0" ];then
        # upgrade ES
        upgrade_es
    fi
            
    if [ "${version}" -lt "551" -a "${version}" -gt "0" ];then
        # remove packages
        rpm -e voipnow-cepstral --nodeps >/dev/null 2>&1
        rpm -e rabbitmq-server --nodeps >/dev/null 2>&1
        rpm -e erlang --nodeps >/dev/null 2>&1
        rpm -e erlang-p1-mysql --nodeps >/dev/null 2>&1
        rpm -e erlang-lager --nodeps >/dev/null 2>&1
        rpm -e erlang-uuid --nodeps >/dev/null 2>&1
        rpm -e erlang-p1-utils --nodeps >/dev/null 2>&1
        rpm -e erlang-esip --nodeps >/dev/null 2>&1
        rpm -e erlang-idna --nodeps >/dev/null 2>&1
        rpm -e erlang-p1-xml --nodeps >/dev/null 2>&1
        rpm -e erlang-cache-tab --nodeps >/dev/null 2>&1
        rpm -e erlang-jsx --nodeps >/dev/null 2>&1
        rpm -e erlang-cache-tab --nodeps >/dev/null 2>&1
        rpm -e erlang-p1-iconv --nodeps >/dev/null 2>&1
        rpm -e erlang-amqp-client --nodeps >/dev/null 2>&1
        rpm -e erlang-p1-oauth2 --nodeps >/dev/null 2>&1
        rpm -e erlang-jiffy --nodeps >/dev/null 2>&1
        rpm -e erlang-luerl --nodeps >/dev/null 2>&1
        rpm -e erlang-p1-xmlrpc --nodeps >/dev/null 2>&1
        rpm -e erlang-fast-yaml --nodeps >/dev/null 2>&1
        rpm -e erlang-svh --nodeps >/dev/null 2>&1        
        rpm -e erlang-goldrush --nodeps >/dev/null 2>&1    
        rpm -e erlang-es --nodeps >/dev/null 2>&1
        rpm -e erlang-stun --nodeps >/dev/null 2>&1
        rpm -e erlang-stringprep --nodeps >/dev/null 2>&1        
        rpm -e erlang-hackney --nodeps >/dev/null 2>&1
        rpm -e erlang-xmlrpc --nodeps >/dev/null 2>&1
        rpm -e erlang-fast-xml --nodeps >/dev/null 2>&1
        rpm -e erlang-fast-tls --nodeps >/dev/null 2>&1
        rpm -e erlang-ezlib --nodeps >/dev/null 2>&1
        rpm -e erlang-rebar --nodeps >/dev/null 2>&1
        rpm -e erlang-p1-cache-tab --nodeps >/dev/null 2>&1
        rpm -e erlang-p1-stringprep --nodeps >/dev/null 2>&1
        rpm -e erlang-p1-tls --nodeps >/dev/null 2>&1
        rpm -e erlang-p1-yaml --nodeps >/dev/null 2>&1
        rpm -e erlang-p1-zlib --nodeps >/dev/null 2>&1
        rpm -e percona-xtrabackup --nodeps >/dev/null 2>&1
        rpm -e voipnow-ejabberd --nodeps >/dev/null 2>&1
        rpm -e hwcelery --nodeps >/dev/null 2>&1
        rpm -e hubgets-strophe --nodeps >/dev/null 2>&1
        rpm -e hubgets-strophe-plugins --nodeps >/dev/null 2>&1
        rpm -e perl-DBD-MariaDB --nodeps >/dev/null 2>&1
        rpm -e ejabberd-mysql --nodeps >/dev/null 2>&1
        rpm -e graphviz --nodeps >/dev/null 2>&1
        rpm -e mysql55-python --nodeps >/dev/null 2>&1
        rpm -e gperftools --nodeps >/dev/null 2>&1
        rpm -e python27-mysql55  --nodeps >/dev/null 2>&1
        rpm -e pprof --nodeps >/dev/null 2>&1
        rpm -e percona-xtrabackup --nodeps >/dev/null 2>&1
        rpm -e voipnow-worker-image --nodeps >/dev/null 2>&1
        rpm -e opencv opencv-python opencv-core --nodeps >/dev/null 2>&1
        rpm -e selinux-policy-collectd --nodeps >/dev/null 2>&1
        rpm -e voipnow-monitoring --nodeps >/dev/null 2>&1
        rpm -e GeoIP-update --nodeps >/dev/null 2>&1
        rpm -e voipnow-monitoring-config --nodeps >/dev/null 2>&1
        rpm -e voipnow-collectd-modules --nodeps >/dev/null 2>&1
        rpm -e collectd --nodeps >/dev/null 2>&1
        rpm -e lame --nodeps >/dev/null 2>&1
        rpm -e tensorflow --nodeps >/dev/null 2>&1
        rpm -e tensorflow-im2txt --nodeps >/dev/null 2>&1
        rpm -e libtensorflow --nodeps >/dev/null 2>&1
        rpm -e python-pbr --nodeps >/dev/null 2>&1
        rpm -e python-hubring --nodeps >/dev/null 2>&1
        rpm -e node-hammer-subscriber --nodeps >/dev/null 2>&1
        rpm -e dahdi-tools --nodeps >/dev/null 2>&1
        rpm -e dahdi-tools-libs --nodeps >/dev/null 2>&1
        rpm -e dahdi-linux --nodeps >/dev/null 2>&1
        rpm -e libtonezone2 --nodeps >/dev/null 2>&1
        if [ "${release}" == "6" ]; then
            rpm -e python3-libs --nodeps >/dev/null 2>&1
            rpm -e python3 --nodeps >/dev/null 2>&1
        fi
        if [ "${WITH_CUDA}" != 1 ];then
            rpm -e cuda --nodeps >/dev/null 2>&1
            rpm -e cuda-drivers --nodeps >/dev/null 2>&1
            rpm -e cuda-nccl --nodeps >/dev/null 2>&1
            rpm -e cuda-cudnn --nodeps >/dev/null 2>&1
        fi
    fi
}

update_os()
{
    if [ ! -d ${voipnowrootd} ];then
        echo
        echo "==> Updating Operating System packages ..."
        echo "This process will take a while..."
        echo
        ${pm} ${step} -c ${pmconf} update ${disablevoipnow}
        if [ "$?" -gt "0" ];then
            die "Could not upgrade Operating System!"
        else
            ok
        fi
    fi
}

beta_warning() {
    if [[ "${beta}" -ne 0 ]];then
        echo
        printf     "${RED}---------------------------------------------------------------------${NC}\n"
        printf    "${RED}This is a Release Candidate version. Do not install it in production!${NC}\n"
        echo
        printf    "${RED}WARNING! NO SUPPORT is available for this software. WARNING!${NC}\n"
        echo
        printf    "${RED}If you need any help with evaluation, please contact 4PSA Help Desk.${NC}\n"
        printf    "${RED}---------------------------------------------------------------------${NC}\n"
        echo
    fi
}

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 ${installer_ver}${installer_tag}."
    echo
    echo
    echo -ne    "You are about to ${action}"
    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
    beta_warning
    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     
        release=`cat /etc/redhat-release | cut -d'.' -f1 | awk '{print $NF}'`
    else
        echo
        echo "${product_name} runs on CentOS and Red Hat Enterprise Linux only!"
        exit 127   
    fi
    
    platform=`uname -i`
    if [ "${platform}" != "x86_64" ];then
        echo
        echo "${product_name} runs only on x86 64 bit platforms only!"
        exit 127
    fi
    
    if [ "${release}" = "6" ];then
        echo
        echo "******************************"
        echo
        echo "This is the LAST VERSION of ${product_name} that runs on CentOS / Red Hat Enterprise Linux versions 6!"
        echo "Please upgrade ASAP to CentOS 8 or Red Hat Enterprise Linux versions 8!"
        echo
        echo "******************************"
        echo
    fi
    
    if [ "${release}" == "7" ];then
        echo
        echo "--------------------------------------------------------------"
        echo
        echo "IMPORTANT - OS NOTICE:"
        echo
        echo "While `cat /etc/redhat-release` is still supported by ${product_name}, we strongly recommend the migration to CentOS 8 or Red Hat Enterprise Linux versions 8!"
        echo "Starting with 2021 Q3, support for `cat /etc/redhat-release` will be discontinued."
        echo
        echo "--------------------------------------------------------------"
        echo
        gpgkey="/etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7"
        crepo="os"
    fi

    if [ "${release}" == "8" ];then
        gpgkey="/etc/pki/rpm-gpg/RPM-GPG-KEY-centosofficial"
        crepo="BaseOS"
    else
        gpgkey="/etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-${release}"
        crepo="os"
    fi
    
    container=0
    if [ -f /proc/1/cgroup ];then
        upproc=`cat /proc/1/cgroup | cut -d: -f3 | sed 's/\///g' | sed '/^\s*$/d' | wc -l`
        if [ "${upproc}" -gt "0" ];then
            container=1
        fi
    fi
    
    if [ "${VNDEBUG}" ];then
        debugrpm='--rpmverbosity=debug'
    else
        debugrpm=''
    fi
}

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

upgrade_mysql()
{

    if [ "${release}" == "6" -o "${release}" == "7" ];then
        rpm -q MariaDB-shared-compat >/dev/null
        if [ "$?" -gt "0" ];then
            ${pm} ${debugrpm} ${step} -c ${pmconf} install MariaDB-shared-compat
        fi
    fi

    if [ "${version}" -gt "300" ];then
        return 1
    fi

    echo
    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 -a -f /etc/voipnow/sqldbase.conf ]; then
            local DB_USER=`grep "^main" /etc/voipnow/.sqldb | cut -d: -f2 2> /dev/null`
            local DB_PASSWD=`grep "^main" /etc/voipnow/.sqldb | cut -d: -f3 2> /dev/null`
            local DB_HOST=`grep "^DB_MASTER\>" /etc/voipnow/sqldbase.conf | awk '{print $2}' | grep "^main" | cut -d: -f2 2> /dev/null`
            local DB_PORT=`grep "^DB_MASTER\>" /etc/voipnow/sqldbase.conf | awk '{print $2}' | grep "^main" | cut -d: -f3 2> /dev/null`
        fi        
    fi
    
    # can we access mysql?
    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%';" >/dev/null 2>&1
        if [ "$?" -gt "0" ];then
            echo "Cannot connect to MySQL server as root, MySQL upgrade will not be performed!"
            return 99
        fi
    else
        return 10
    fi
            
    mysql -h${DB_HOST} -P${DB_PORT} -u${DB_USER} -p${DB_PASSWD} -e"SHOW VARIABLES LIKE '%version%';" 2>/dev/null | grep -i "${mariadb_ver}" | grep -i "mariadb" > /dev/null
    if [ "$?" -gt "0" ];then
        my_upgrade=1
    fi

    ${pm} ${debugrpm} ${step} -c ${pmconf} update MariaDB-server MariaDB-client MariaDB-shared
    
    if [ "$?" -gt "0" ];then
        die "Could not complete MySQL and dependencies upgrade!"
    else
        if [ "${my_upgrade}" == "1" ];then
            mysql_upgrade -h${DB_HOST} -P${DB_PORT} -u${DB_USER} -p${DB_PASSWD} >/dev/null 2>&1
            if [ "$?" -gt "0" ];then
                echo "Cannot upgrade MySQL schema. MySQL server might not work correctly!"
            else
                service mysql restart
            fi
        fi
    fi
}

install_with_pm()
{
    
    ${pm} ${step} -c ${pmconf} clean metadata >/dev/null 2>&1
        
    if [ "${action1}" == "upgrade" ];then
    
        upgrade_mysql
            
        echo
        echo "===> Updating ${product_name} base components..."
        ${pm} ${debugrpm} ${step} -c ${pmconf} upgrade
        if [ "$?" -gt "0" ];then
            die "Could not complete ${product_name} base components update!"
        fi
        
        echo
        echo "===> Updating ${product_name} core..."
        ${pm} ${debugrpm} ${step} -c ${pmconf} install voipnow-webmanagement hubgets-page-js

        if [ "$?" -gt "0" ];then
            die "Could not complete ${product_name} core update!"
        fi
        
        if [ "${vac_installed}" == "1" ];then
            ${pm} ${debugrpm} ${step} -c ${pmconf} install voipnow-asterisk-codec-g729
        fi
    else
        echo
        echo "==> Performing ${product_name} ${action1}..."
        echo    

        ${pm} ${debugrpm} ${step} -c ${pmconf} install voipnow-webmanagement hubgets-page-js
        if [ "$?" -gt "0" ];then
            die "Could not complete ${product_name} ${action1}!"
        fi
        
        if [ "${vac_installed}" == "1" ];then
            ${pm} ${debugrpm} ${step} -c ${pmconf} install voipnow-asterisk-codec-g729
        fi
        
    fi
    
    # workaround for mysql
    /sbin/chkconfig --add mysql 2>/dev/null || :
    
    node_restart
}

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 pre-required packages..."
        ${pm} -c ${pmconf} -y install procmail >/dev/null 2>&1
        if [ "$?" -gt "0" ];then
            die "Could not install all pre-required packages!"
        else
            echo "OK!"
            echo
        fi
    fi
}

check_av_updates()
{
    if [ -d ${voipnowrootd} ]; then
        pm_output=`${pm} -q -c ${pmconf} check-update --disablerepo=base --disablerepo=updates --disablerepo=epel | grep -v "\-devel" | grep -v "\-debuginfo" | sed '/^$/d'`
        no_updates=`echo "${pm_output}" | sed '/^$/d' | wc -l`
        remote_version=`echo "${pm_output}" | grep -w "voipnow-core" | head -1 | awk '{print $2}' | cut -d'-' -f1 | sed 's/\.//g'`

        if [ -z "${no_updates}" ];then
            no_updates=0
        fi
    fi
}

check_installer()
{
    local major_remote=`echo ${remote_version} | cut -c 1-2`
    local major_local=`echo ${installer_ver} | sed 's/\.//g' | cut -c 1-2`
    local int_local=`echo ${installer_ver} | sed 's/\.//g'`

    if [ -n "${remote_version}" ];then
        if [ "${major_remote}" != "${major_local}" ];then
            echo
            echo "You are using an older version of ${product_name} installer."
            die "Visit https://wiki.4psa.com/display/VNDOCS30/Command+Line+Installer to download the latest installer."
        fi
    fi
    
    if [ "${version}" -gt "${int_local}" ];then
        echo
        echo "You are running ${product_name} ${versionf}".
        echo "Requested upgrade version (${installer_ver}${installer_tag}) is inferior."
        die "Please download a correct installer!"
    fi
}


get_pmconf()
{
    local repo=''
    curl -f --connect-timeout 20 -L ${origin} -o ${repolocal} >/dev/null 2>&1
    if [ ! -f ${repolocal} ];then
        die "Could not download from origin: ${origin}"
    fi
           
    # Replace the standard destination with another one
    dsite_host=`echo ${dsite} | awk -F/ '{url=$1"//"$3; print url}'`
    
    local alldeps=`grep "^http" ${repolocal} | sed -e "s#http.*://download2.4psa.com#${dsite_host}#g"`
    
    if [ -z "${alldeps}" ];then
        die "Repository file downloaded from ${origin} is invalid!"
    fi
    
    if [ -f ${pmconf} ];then
        mv -f ${pmconf} ${pmconf}.old
    fi
    
    cat <<EOT > ${pmconf}
[main]
cachedir=/var/cache/voipnow
keepcache=0
debuglevel=2
logfile=${update_log}
diskspacecheck=1
exactarch=1
obsoletes=1
metadata_expire=300
installonly_limit=3
reposdir=./
exclude=${exclude_pack}
plugins=1
ip_resolve=4

EOT
            
    for repo in ${alldeps};do
        curl -f --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}"
            
            disablevoipnow="${disablevoipnow} --disablerepo=${localrepo}"
            
            cat local$$ | sed -e "s#http.*://download2.4psa.com#${dsite_host}#g" >> ${pmconf}
            echo >> ${pmconf}
            rm -f local$$
        else
            die "Could not download from origin repo: ${repo}"
        fi
    done
    
    # Modify hubwall to skip module checks
    if [ "${release}" == "8" ];then
        sed -i '/\[hubwall-/ a module_hotfixes=True' ${pmconf}
    
    fi
    
    # Comment mirrors if needed
    if [ "${cm}" -eq "1" ];then
        sed -i -e "s/mirrorlist=/#mirrorlist=/g" ${pmconf}
        if [ "${SIGN_CHECK}" == "0" ];then
            sed -i -e "s/gpgcheck=1/gpgcheck=0/g" ${pmconf}        
        fi
    fi
    
    # Add OS repositories
    
    if [ "${release}" == "6" ];then

        cat <<EOT >> ${pmconf}

[base]
name=CentOS-\$releasever - Basemirrorlist=http://mirrorlist.centos.org/?release=\$releasever&arch=\$basearch&repo=${crepo}
baseurl=http://vault.centos.org/centos/\$releasever/os/\$basearch/
gpgcheck=1
gpgkey=file://${gpgkey}

[updates]
name=CentOS-\$releasever - Updates
baseurl=http://vault.centos.org/centos/\$releasever/updates/\$basearch/
gpgcheck=1
gpgkey=file://${gpgkey}
EOT
    
    else

        cat <<EOT >> ${pmconf}
        
[base]
name=CentOS-\$releasever - Base
mirrorlist=http://mirrorlist.centos.org/?release=\$releasever&arch=\$basearch&repo=${crepo}&infra=\$infra
#baseurl=http://mirror.centos.org/centos/\$releasever/os/\$basearch/
gpgcheck=1
gpgkey=file://${gpgkey}
EOT
    fi
    

    if [ "${release}" == "7" ];then
        cat <<EOT >> ${pmconf}

[updates]
name=CentOS-\$releasever - Updates
mirrorlist=http://mirrorlist.centos.org/?release=\$releasever&arch=\$basearch&repo=updates&infra=\$infra
gpgcheck=1
gpgkey=file://${gpgkey}
EOT
    fi

    if [ "${release}" == "8" ];then
        cat <<EOT >> ${pmconf}

[AppStream]
name=CentOS-\$releasever - AppStream
mirrorlist=http://mirrorlist.centos.org/?release=\$releasever&arch=\$basearch&repo=AppStream&infra=\$infra
gpgcheck=1
enabled=1
gpgkey=file://${gpgkey}

[PowerTools]
name=CentOS-\$releasever - PowerTools
mirrorlist=http://mirrorlist.centos.org/?release=\$releasever&arch=\$basearch&repo=PowerTools&infra=\$infra
gpgcheck=1
enabled=1
gpgkey=file://${gpgkey}
EOT
    fi
    cat <<EOT >> ${pmconf}    

[epel]
name=Extra Packages for Enterprise Linux \$releasever - \$basearch
#baseurl=http://download.fedoraproject.org/pub/epel/\$releasever/Everything/\$basearch
metalink=https://mirrors.fedoraproject.org/metalink?repo=epel-\$releasever&arch=\$basearch&infra=\$infra&content=\$contentdir
enabled=1
gpgcheck=1
gpgkey=https://download.fedoraproject.org/pub/epel/RPM-GPG-KEY-EPEL-${release}
EOT
    return 0
}

install_mysql()
{
    # start installation only when not installed
    if [ ! -f /etc/voipnow/.mysql ];then
        echo
        echo "==> Starting ${product_name} procedure."
        echo "This process will take a while ..."
        echo

        # performs installation
        ${pm} ${step} -c ${pmconf} 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
    fi
}

# Fixes the values in my.cnf on mysql dedicated nodes only
my_fix()
{
    if [ -f ${_sysconfdir}/my.cnf ];then
        grep "^[mysqld]" ${_sysconfdir}/my.cnf >/dev/null
        if [ "$?" -gt "0" ];then
            echo "==> Fixing my.cnf settings"
            echo >> ${_sysconfdir}/my.cnf
            sed -i -e "\$a[mysqld]" ${_sysconfdir}/my.cnf
            my_upgrade=1
        fi

        grep "^max-connections" ${_sysconfdir}/my.cnf >/dev/null
        if [ "$?" -gt "0" ];then
            sed -i -e 's/\[mysqld\]/[mysqld]\nmax-connections=1500/g' ${_sysconfdir}/my.cnf
            my_upgrade=1
        fi
    
        grep "^character-set-server" ${_sysconfdir}/my.cnf >/dev/null
        if [ "$?" -gt "0" ];then
            sed -i -e 's/\[mysqld\]/[mysqld]\ncharacter-set-server=utf8/g' ${_sysconfdir}/my.cnf
            my_upgrade=1
        fi
    
        grep "^interactive_timeout" ${_sysconfdir}/my.cnf >/dev/null
        if [ "$?" -gt "0" ];then
            sed -i -e 's/\[mysqld\]/[mysqld]\ninteractive_timeout=900/g' ${_sysconfdir}/my.cnf
            my_upgrade=1
        fi
    
        grep "^wait_timeout" ${_sysconfdir}/my.cnf >/dev/null
        if [ "$?" -gt "0" ];then
            sed -i -e 's/\[mysqld\]/[mysqld]\nwait_timeout=900/g' ${_sysconfdir}/my.cnf
            my_upgrade=1
        fi
        
        grep "^max_connect_errors" ${_sysconfdir}/my.cnf >/dev/null
        if [ "$?" -gt "0" ];then
            sed -i -e 's/\[mysqld\]/[mysqld]\nmax_connect_errors=4294967295/g' ${_sysconfdir}/my.cnf
            my_upgrade=1
        fi
    
        grep "^default-storage_engine" ${_sysconfdir}/my.cnf >/dev/null
        if [ "$?" -gt "0" ];then
            sed -i -e 's/\[mysqld\]/[mysqld]\ndefault-storage_engine=InnoDB/g' ${_sysconfdir}/my.cnf
            my_upgrade=1
        fi
    
        grep "^max_allowed_packet" ${_sysconfdir}/my.cnf >/dev/null
        if [ "$?" -gt "0" ];then
            sed -i -e 's/\[mysqld\]/[mysqld]\nmax_allowed_packet=10M/g' ${_sysconfdir}/my.cnf
            my_upgrade=1
        fi
    
        grep "^event-scheduler" ${_sysconfdir}/my.cnf >/dev/null
        if [ "$?" -gt "0" ];then
            sed -i -e 's/\[mysqld\]/[mysqld]\nevent-scheduler=on/g' ${_sysconfdir}/my.cnf
            my_upgrade=1
        fi
    
        grep "^ignore_builtin_innodb" ${_sysconfdir}/my.cnf >/dev/null
        if [ "$?" -gt "0" ];then
            sed -i -e '/^ignore_builtin_innodb/d' ${_sysconfdir}/my.cnf
            my_upgrade=1
        fi
    
        grep "^plugin-load=innodb=ha_innodb_plugin.so;" ${_sysconfdir}/my.cnf >/dev/null
        if [ "$?" -gt "0" ];then
            sed -i -e '/^plugin-load=innodb=ha_innodb_plugin.so;/d' ${_sysconfdir}/my.cnf
            my_upgrade=1
        fi
        
        grep "^transaction_isolation=READ-COMMITTED" ${_sysconfdir}/my.cnf >/dev/null
        if [ "$?" -gt "0" ];then
            sed -i -e 's/\[mysqld\]/[mysqld]\ntransaction_isolation=READ-COMMITTED/g' ${_sysconfdir}/my.cnf
            my_upgrade=1
        fi
        
        grep "^default-time-zone=\"utc\"" ${_sysconfdir}/my.cnf >/dev/null
        if [ "$?" -gt "0" ];then
            sed -i -e 's/\[mysqld\]/[mysqld]\ndefault-time-zone="utc"/g' ${_sysconfdir}/my.cnf
            my_upgrade=1
        fi
        
        grep "^net_read_timeout" ${_sysconfdir}/my.cnf >/dev/null
        if [ "$?" -gt "0" ];then
            sed -i -e 's/\[mysqld\]/[mysqld]\nnet_read_timeout=60/g' ${_sysconfdir}/my.cnf
            my_upgrade=1
        fi
        
        grep "^net_write_timeout" ${_sysconfdir}/my.cnf >/dev/null
        if [ "$?" -gt "0" ];then
            sed -i -e 's/\[mysqld\]/[mysqld]\nnet_write_timeout=120/g' ${_sysconfdir}/my.cnf
            my_upgrade=1
        fi
        
        grep "^init-connect" ${_sysconfdir}/my.cnf >/dev/null
        if [ "$?" -gt "0" ];then
            sed -i -e 's/\[mysqld\]/[mysqld]\ninit-connect="SET NAMES utf8"/g' ${_sysconfdir}/my.cnf
            my_upgrade=1
        fi
        
        grep "^datadir" ${_sysconfdir}/my.cnf >/dev/null
        if [ "$?" -gt "0" ];then
            sed -i -e 's/\[mysqld\]/[mysqld]\ndatadir=\/var\/lib\/mysql/g' ${_sysconfdir}/my.cnf
            my_upgrade=1
        fi
        
        grep "^innodb_file_per_table" ${_sysconfdir}/my.cnf >/dev/null
        if [ "$?" -gt "0" ];then
            sed -i -e 's/\[mysqld\]/[mysqld]\ninnodb_file_per_table=1/g' ${_sysconfdir}/my.cnf
            my_upgrade=1
        fi
        
        grep "^sql-mode" ${_sysconfdir}/my.cnf >/dev/null
        if [ "$?" -gt "0" ];then
            sed -i -e 's/\[mysqld\]/[mysqld]\nsql-mode="NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"/g' ${_sysconfdir}/my.cnf
            my_upgrade=1
        fi
        
        grep "^innodb-buffer-pool-size" ${_sysconfdir}/my.cnf >/dev/null
        if [ "$?" -gt "0" ];then
            sed -i -e 's/\[mysqld\]/[mysqld]\ninnodb-buffer-pool-size=32M/g' ${_sysconfdir}/my.cnf
            my_upgrade=1
        fi    
    else
        echo '[mysqld]' > ${_sysconfdir}/my.cnf
        echo 'max-connections=1500' >> ${_sysconfdir}/my.cnf
        echo 'character-set-server=utf8' >> ${_sysconfdir}/my.cnf
        echo 'interactive_timeout=900' >> ${_sysconfdir}/my.cnf
        echo 'wait_timeout=900' >> ${_sysconfdir}/my.cnf
        echo 'default-storage_engine=InnoDB' >> ${_sysconfdir}/my.cnf
        echo 'max_allowed_packet=10M' >> ${_sysconfdir}/my.cnf
        echo 'event-scheduler=on' >> ${_sysconfdir}/my.cnf
        echo 'transaction_isolation=READ-COMMITTED' >> ${_sysconfdir}/my.cnf
        echo 'default-time-zone="utc"' >> ${_sysconfdir}/my.cnf
        echo 'max_connect_errors=4294967295' >> ${_sysconfdir}/my.cnf
        echo 'net_read_timeout=60' >> ${_sysconfdir}/my.cnf
        echo 'net_write_timeout=120' >> ${_sysconfdir}/my.cnf
        echo 'init-connect="SET NAMES utf8"' >> ${_sysconfdir}/my.cnf
        echo 'datadir=/var/lib/mysql' >> ${_sysconfdir}/my.cnf
        echo 'innodb_file_per_table=1' >> ${_sysconfdir}/my.cnf
        echo 'sql-mode="NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"' >> ${_sysconfdir}/my.cnf
        echo 'innodb-buffer-pool-size=32M' >> ${_sysconfdir}/my.cnf
        my_upgrade=1
    fi
}

mysql_setup()
{
    # only on master node
    if [ "${this_is_slave}" == "0" ];then
        # do nothing if the node is installed
        if [ -f ${voipnowcredentials} ];then
            my_fix
            return 0
        elif [ "${ALT_DB_USER}" -a "${ALT_DB_PASSWD}" -a "${ALT_DB_PORT}" -a "${ALT_DB_HOST}" -a "${ALT_DB_NAME}" ];then
            my_fix
            return 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 "SET PASSWORD FOR 'root'@'localhost' = PASSWORD('${dbpass}'); RENAME USER 'root'@'localhost' TO '${dbuser}'@'localhost';FLUSH PRIVILEGES;" mysql || die "Could not change the root MySQL password!"
        
        my_fix
        
        # just to make sure
        if [ "${my_upgrade}" == "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
    service httpsa stop 2>/dev/null || :
    chkconfig httpsa off 2>/dev/null || :    
}

ask_things()
{
    # executes on master only
    if [ "${this_is_slave}" == "0" ];then

        # we have an existing installation locally
        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!"
                echo
                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%';" >/dev/null 2>&1
            
            if [ "$?" -gt "0" ];then
                echo "Could not connect to MySQL with provided credentials!"
                echo
                echo "Please fix the error by exporting correct ALT_DB_HOST, ALT_DB_PORT, ALT_DB_USER and ALT_DB_PASSWD"
                echo
                exit 1
            fi
        else
        
            local suggestip="192.168.1.3"    
            local localip=`ip addr | grep -Ev "127.0.0.1|inet6|docker" | grep -i "inet" | head -1 | awk '/inet/{print $2}' | cut -d/ -f1 | awk '{print $1}'`

            if [ -n "${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
                ip addr | 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}" == "4" ];then
                        die "Exiting ..."
                   else
                        echo "Please try another IP."
                   fi
                fi
                (( counter++ ))
            done

            DB_HOST=${dbhost}
        fi
    fi
}

save_settings()
{
    if [ "${this_is_slave}" == "0" ];then
        if [ -f ${voipnowcredentials} ];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!"
        
        voipnowcredentialsdir=`dirname ${voipnowcredentials}`
        
        if [ ! -d ${voipnowcredentialsdir} ];then
            mkdir ${voipnowcredentialsdir}
        fi
        
        echo "# This file contains MySQL server credentials" > ${voipnowcredentials}
        echo "DO NOT DELETE IT!" >> ${voipnowcredentials}

        chmod 600 ${voipnowcredentials}

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

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

determine_op()
{
    get_install_type
    local x=$?
    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_HOST}:${ALT_DB_PORT}\n\nUsername: ${ALT_DB_USER}\nPassword: ${ALT_DB_PASSWD}\nDatabase: ${ALT_DB_NAME}"
            action1="installation"
        ;;
        3)
            action="upgrade this VoipNow ${versionf} node.\n\nThere are ${GREEN}${no_updates}${NC} packages for upgrade (excluding Operating System).\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 https://wiki.4psa.com/display/VNDOCS30/Distributed+System+Deployment before continuing"
            action1="installation"
        ;;
        5)
            action="install a MySQL node for VoipNow.\n\nPlease read https://wiki.4psa.com/display/VNDOCS30/Distributed+System+Deployment before continuing"
            action1="installation"
        ;;
    esac
}

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

check_cpu()
{
    if [ "${check}" == "1" -o "${this_is_mysql}" == "1" ];then
        return 0
    fi
    
    grep -m1 -o aes /proc/cpuinfo > /dev/null
    if [ "$?" -gt "0" ];then
        echo "Your CPU is not supported."
        die "Please upgrade to a newer generation CPU that supports AES-NI instruction set."    
    fi
    
    availmem=`free -m | grep "Mem:" | awk '{print $2}'`
    if [ "${availmem}" -lt "8000" ];then
        echo "Not enough system memory (RAM)."
        if [ "${IGNORERAM}" != "1" ];then
            die "Please upgrade to minimum 8GB. 16GB or more is recommended."
        fi
    fi
}

get_variables()
{
    if [ -f ${config_main} ];then
        DB_USER=`grep "^DB_CREDENTIALS\>" ${config_main} | awk '{print $2}' | grep "^main" | cut -d: -f2`    
        DB_PASSWD=`grep "^DB_CREDENTIALS\>" ${config_main} | awk '{print $2}' | grep "^main" | cut -d: -f3`    
        DB_NAME=`grep "^DB_CREDENTIALS\>" ${config_main} | awk '{print $2}' | grep "^main" | cut -d: -f4`
        DB_HOST=`grep "^DB_MASTER\>" ${config_sqldbase} | awk '{print $2}' | grep "^main" | cut -d: -f2`
        DB_PORT=`grep "^DB_MASTER\>" ${config_sqldbase} | awk '{print $2}' | grep "^main" | cut -d: -f3`
    fi
}

check_db()
{
    if [ -f ${config_main} ];then
        # check for MySQL
        no_recs_ch=`mysql -h${DB_HOST} -P${DB_PORT} -u${DB_USER} -p${DB_PASSWD} -N -e"SELECT table_rows 'Rows Count' FROM information_schema.tables WHERE table_name='call_history' AND table_schema='${DB_NAME}'" 2>/dev/null`

        if [ -n "${no_recs_ch}" ];then
            if [ "${no_recs_ch}" -ge 1000000 ];then
                # has been the table altered?
                mysql -h${DB_HOST} -P${DB_PORT} -u${DB_USER} -p${DB_PASSWD} -e"SHOW COLUMNS FROM voipnow.extension_fax_center LIKE 'callid';" | grep -i "decimal" >/dev/null 2>&1
                if [ "$?" -gt "0" ];then
                    echo "It seems that your MySQL database is large and has not been upgraded yet to VoipNow 5 pre-upgrade schema."
                    die "Please upgrade the database before going further, for more information check the Release Notes!"
                fi
            fi
        fi
        
        # check hubring
        local hubring_ver=`rpm -qi hubring | grep "^Version" | cut -d: -f2 | sed 's/\.//g' | awk '{print $1}'`
        if [ "${hubring_ver}" -lt "250" ];then
            # lets check for distribution
            hubring_no=`mysql -h${DB_HOST} -P${DB_PORT} -u${DB_USER} -p${DB_PASSWD} ${DB_NAME} -N -e"SELECT count(id) FROM node_role WHERE role='dd' AND status=1"`
            if [ "${hubring_no}" -gt "1" ];then
                echo
                echo "UPGRADE NOTE: Hubring cluster detected!"
                echo
                echo "Your deployment cannot be upgraded automatically. Please contact 4PSA Help Desk."    
                echo
                exit 1
            fi
        fi
    fi
}

final_warnings()
{
    UPGRADE_FAIL=0
    local no_error=`cat ${error_log_dir}/install_error.log 2>/dev/null | wc -l`
    if [ "${no_error}" -gt "0" ];then
        echo
        echo
        echo "================================================================"
        echo
        
        echo "We detected the following CRITICAL problems during the installation:"
        echo
        cat ${error_log_dir}/install_error.log
        echo
        echo "Please contact our team in the 4PSA Help Desk"
        echo "and quote this log in the ticket!"
        echo
        echo "================================================================"
        echo
        
        UPGRADE_FAIL=1
    fi
}

# main
cd `dirname $0`
repolocal=repo.dep$$
pmconf=/etc/voipnow-yum.conf
config_sqldbase=/etc/voipnow/sqldbase.conf
config_main=/etc/voipnow/main.conf
voipnowrepo=''
disablevoipnow=''
step='-y'
this_is_mysql=0
this_is_slave=0
vac_installed=0
auto=0
check=0
my_upgrade=0
version=0

echo

get_variables
check_db
is_root

# 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

# Necessary until sysctl is modified
ulimit -n 32768

# This is installation
check_cpu
log_general "Started: Installer with auto=${auto}"
prepare_log
check_os
detect_version
friendly_wait
check_deps
origin_find
get_pmconf
check_av_updates
    
if [ "${check}" == "1" ];then
    rm -f ${repolocal} local$$
    echo "Available ${no_updates} updates!"
    exit ${no_updates}
fi

check_installer
determine_op

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

check_minver

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

post_selinux
rm -f /var/lock/subsys/vninstaller

final_warnings
    
exit ${UPGRADE_FAIL}
