#!/bin/bash -e

. ./fusion-sys.cfg

# Was previous step completed?
if [ ! -f installed.database ]; then
    echo "Database was not properly installed" >&2
    exit 1
fi

# Is general already installed?
if [ -f installed.general ]; then
    echo "General configuration already applied - skipping..."
    exit 0
fi

# ================
# SElinux
# ----------------

# Set SELinux to disabled
if selinuxenabled; then
    setenforce 0
    cp -r inc/selinux /etc/selinux/config
fi

# ================
# Date & Time
# ----------------

# Set timezone in PHP script (this will also be done by the PHP on final install)
if [ -r /etc/sysconfig/clock ]; then
    . /etc/sysconfig/clock
    sed -i "s~^;date\.timezone =$~date.timezone = $ZONE~" "$phpini" || true
elif [ `command -v timedatectl` ]; then
    timezone=$(timedatectl | awk '/Time zone:/ {print $3}')
    sed -i "s~^;date\.timezone =$~date.timezone = $timezone~" "$phpini" || true
fi

# ================
# Firewall
# ----------------

# Skip firewall configuration for Ubuntu for now
if [ "$distro" == "Ubuntu" ] || [ "$distro" == "Debian" ]; then
    echo "Skipping firewall configuration... Not enabled."
else
    # Firewalld settings for CentOS/RHEL 7 and 8 (except 7.2)
    if [ "$dist" == "el7" ] || [ "$dist" == "el8" ] || [ "$dist" == "el9" ]; then
        set +e
        if [ `command -v firewall-cmd` ]; then
            firewall-cmd --zone=public --add-port=80/tcp --permanent
            firewall-cmd --zone=public --add-port=403/tcp --permanent
            firewall-cmd --zone=public --add-port=22/tcp --permanent
            firewall-cmd --reload
        fi
        set -e
    else
        cp -f inc/iptables /etc/sysconfig
        service iptables restart
    fi
fi

# ================
# Services
# ----------------

# Special case for CentOS 7 & mariadb
if [ "$dist" == "el7" ] || [ "$dist" == "el8" ] || [ "$dist" == "el9" ] || [ "$dist" == "debian10" ] || [ "$dist" == "debian11" ] || [ "$dist" == "debian12" ]; then

    # Enable in systemctl
    for svc in $ntpd $mysqld $crond $httpd $sendmail; do
        systemctl enable "$svc"
    done

elif [ "$distro" == "Ubuntu" ] || [ "$distro" == "Debian" ]; then

    for svc in $mysqld $httpd $ntpd $crond $sendmail; do
        update-rc.d "$svc" defaults
    done

else

    # For CentOS 6
    for svc in $mysqld $httpd $ntpd $crond; do
        chkconfig --level    35 "$svc" on
        chkconfig --level 01246 "$svc" off
    done

fi

for svc in $httpd $crond $sendmail; do
    service $svc restart || exit 1
done


echo "General configuration setup OK"
touch installed.general