#!/bin/bash

#
# Copyright (C) 2017 Nethesis S.r.l.
# http://www.nethesis.it - support@nethesis.it
#
# This script is part of NethServer.
#
# NethServer is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License,
# or any later version.
#
# NethServer is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with NethServer.  If not, see <http://www.gnu.org/licenses/>.
#

# check if fpbx is already installed
if [[ -f /var/www/html/freepbx/index.php ]] ; then
    diff -q /usr/src/freepbx/amp_conf/bin/retrieve_conf /var/lib/asterisk/bin/retrieve_conf >/dev/null
    files_differ=$?
    grep -q 'if (version_compare($version, "11", "lt") || version_compare($version, "17", "ge")) {' /var/lib/asterisk/bin/retrieve_conf
    version_control=$?
    if [[ $files_differ == 1 && $version_control == 0 ]]; then
        echo "Patching /var/lib/asterisk/bin/retrieve_conf to allow Asterisk 18"
        /bin/cp /usr/src/freepbx/amp_conf/bin/retrieve_conf /var/lib/asterisk/bin/retrieve_conf
    fi

    # don't launch installation since FreePBX is already installed
    exit 0
fi

source /opt/rh/rh-php56/enable

# run install
pass=$(perl -e  'use NethServer::Password; print NethServer::Password::store('mysql');')
cd /usr/src/freepbx
./install --dbuser root --dbpass $pass --webroot /var/www/html/freepbx -n >> /var/log/freepbx_rpm_install.log 2>&1

/usr/bin/mysql --defaults-file=/root/.my.cnf -N --batch asterisk -e 'SELECT `data` FROM `module_xml` WHERE `id`="randomid"' > /etc/asterisk/freepbx-id

# refresh fpbx signatures of files and reload
echo -e "[modules]\nautoload=yes" >> /etc/asterisk/asterisk.conf
/usr/sbin/fwconsole chown >> /var/log/freepbx_rpm_install.log 2>&1
exec /usr/sbin/fwconsole r >> /var/log/freepbx_rpm_install.log 2>&1

