#!/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/>.
#

systemd-tmpfiles --create /usr/lib/tmpfiles.d/httpd-fpbx.conf

# check if fpbx is already installed
if [[ -f /var/www/html/freepbx/index.php ]] ; then
    exit 0
fi

#new install call install
echo " *** Installing FreePBX *** see /var/log/freepbx_rpm_install.log"
echo " *** Installing FreePBX" >> /var/log/freepbx_rpm_install.log
/usr/bin/date >> /var/log/freepbx_rpm_install.log

mkdir -p /var/lib/asterisk/sounds/custom/

# wait for asterisk
systemctl start asterisk

touch /var/log/asterisk/fail2ban
touch /var/log/asterisk/freepbx_security.log
touch /var/log/asterisk/cdr-csv/Master.csv
touch /etc/asterisk/pjsip_wizard.conf

chmod 666 /var/log/asterisk/cdr-csv/Master.csv
chmod 755 /var/spool/asterisk/monitor 2>/dev/null

mkdir -p /var/log/pbx/install
mkdir -p /var/log/pbx/upgrade

mkdir -p /etc/asterisk/keys

chown -R asterisk:asterisk /var/run/asterisk /var/log/pbx /var/lib/asterisk/sounds /etc/asterisk /var/log/asterisk/ /etc/asterisk/pjsip_wizard.conf

chmod -R 755 /etc/asterisk
chmod 750 /etc/asterisk/keys

sed -i 's/memory_limit = 128M/memory_limit = 256M/' /etc/opt/rh/rh-php56/php.ini

#Use bash shell for asterisk user
echo "Making sure asterisk user has bash as shell" >> /var/log/freepbx_rpm_install.log
/usr/sbin/usermod --shell /bin/bash asterisk &>> /var/log/freepbx_rpm_install.log
#Check Asterisk user has home dir
if [[ ! -d /home/asterisk ]]; then
    echo "Creating Asterisk user home dir" >> /var/log/freepbx_rpm_install.log
    /usr/sbin/mkhomedir_helper asterisk &>> /var/log/freepbx_rpm_install.log
fi

# Avoid loginctl stale sessions for asterisk user
loginctl enable-linger asterisk

exit 0
