#!/bin/bash
#-----------------------------------------------------------------------------#
# eFa 4.0.4 post initial configuration script
#-----------------------------------------------------------------------------#
# Copyright (C) 2013~2022 https://efa-project.org
#
# This program 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
# (at your option) any later version.
#
# This program 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 this program.  If not, see <http://www.gnu.org/licenses/>.
#-----------------------------------------------------------------------------#

############################## PRECHECK #######################################
# Things that must be done before initializing
###############################################################################

# Don't run if reboot is pending
[[ -f /reboot.system ]] && exit 0

# Don't run if lock is present and more than one instance
if [[ -f /var/run/eFa-Post-Init.lock ]]; then
  # Check for running process
  CHECKPOST=$(ps -ef | grep eFa-Post-Init | wc -l)
  if [[ $CHECKPOST -gt 3 ]]; then
    # Another post init is running, exit now
    exit 0
  fi
fi

# Create lock file
touch /var/run/eFa-Post-Init.lock

centosver=$(cat /etc/centos-release | awk -F'[^0-9]*' '{print $2}')

# Reset footer
sed -i "/^    echo ' running on ' . efa_version/ c\    echo ' running on ' . efa_version() . ' ...INITIALIZING SYSTEM, PLEASE WAIT... ';" /var/www/html/mailscanner/functions.php

# Remove eFaInit config if present
[[ -f /etc/httpd/conf.d/eFaInit.conf ]] && rm -f /etc/httpd/conf.d/eFaInit.conf

# Cleanup init files
[[ -d /var/www/eFaInit ]] && rm -rf /var/www/eFaInit
[[ -f /usr/sbin/eFa-Init ]] && rm -f /usr/sbin/eFa-Init
[[ -f /usr/sbin/eFa-Commit ]] && rm -f /usr/sbin/eFa-Commit

# Retrieve gateways for ipv4 and ipv6
IPV4GATEWAY=$(/usr/sbin/ip -4 route list default | awk {'print $3'})
IPV6GATEWAY=$(/usr/sbin/ip -6 route list default | awk {'print $3'})

# Ensure unbound is running
systemctl start unbound

# Do we have Internet access?

if [[ -n $IPV4GATEWAY ]]; then
  wget -q --tries=3 --timeout=20 --spider https://ipv4.efa-project.org
  if [[ $? -ne 0 ]]; then
    logger -p user.warn "eFa Post Init: No Internet access detected over IPV4!  Please fix me to finish initializing eFa.  Retrying in 1 minute..."
    sed -i "/^    echo ' running on ' . efa_version/ c\    echo ' running on ' . efa_version() . ' ...ERROR INITIALIZATING IPV4, CHECK INTERNET ACCESS... ';" /var/www/html/mailscanner/functions.php
    rm -f /var/run/eFa-Post-Init.lock
    exit 1
  fi
fi

if [[ -n $IPV6GATEWAY && -z $(grep 'do-ip6: no' /etc/unbound/unbound.conf) ]]; then
  wget -q --tries=3 --timeout=20 --spider https://ipv6.efa-project.org
  if [[ $? -ne 0 ]]; then
    logger -p user.warn "eFa Post Init: No Internet access detected over IPV6!  Please fix me to finish initializing eFa.  Retrying in 1 minute..."
    sed -i "/^    echo ' running on ' . efa_version/ c\    echo ' running on ' . efa_version() . ' ...ERROR INITIALIZATING IPV6, CHECK INTERNET ACCESS... ';" /var/www/html/mailscanner/functions.php
    rm -f /var/run/eFa-Post-Init.lock
    exit 1
  fi
fi

if [[ -z $IPV4GATEWAY && -z $IPV6GATEWAY ]]; then
  logger -p user.warn "eFa Post Init: No Internet access detected because no gateway is set!  Please fix me to finish initializing eFa.  Retrying in 1 minute..."
  sed -i "/^    echo ' running on ' . efa_version/ c\    echo ' running on ' . efa_version() . ' ...ERROR INITIALIZATING, CHECK INTERNET ACCESS GATEWAYS... ';" /var/www/html/mailscanner/functions.php
  rm -f /var/run/eFa-Post-Init.lock
  exit 1
fi

############################## EARLY PHASE ###################################
# Tasks that must happen before allowing email to relay
##############################################################################

# Early daemon restart

# Early asynchronous tasks

# /usr/bin/mailwatch/tools/Cron_jobs/mailwatch_geoip_update.php &

/bin/sa-update &

# Early synchronous tasks

# Initial clamav unofficial sigs download
sed -i '/^enable_random/ c\enable_random="no"' /etc/clamav-unofficial-sigs/master.conf
systemctl stop clamav-unofficial-sigs
systemctl stop clamav-unofficial-sigs.timer
/usr/sbin/clamav-unofficial-sigs.sh --force
if [[ $? -ne 0 ]]; then
    logger -p user.warn "eFa Post Init: ClamAV Unofficial Sigs download failed!  Please fix me to finish initializing eFa.  Retrying in 1 minute..."
    sed -i "/^    echo ' running on ' . efa_version/ c\    echo ' running on ' . efa_version() . ' ...ERROR INITIALIZATING, CHECK clamav unofficial sigs... ';" /var/www/html/mailscanner/functions.php
    rm -f /var/run/eFa-Post-Init.lock
    exit 1
fi
sed -i '/^enable_random/ c\enable_random="yes"' /etc/clamav-unofficial-sigs/master.conf
systemctl start clamav-unofficial-sigs
systemctl start clamav-unofficial-sigs.timer

if [[ ! -f /var/lib/clamav/main.cvd ]]; then
  systemctl stop clamd@scan

  freshclam

  systemctl start clamd@scan
  if [[ $? -ne 0 ]]; then
    # Error!  Try again...
    logger -p user.warn "eFa Post Init: Clamd restart failed!  Please fix me to finish initializing eFa.  Retrying in 1 minute..."
    sed -i "/^    echo ' running on ' . efa_version/ c\    echo ' running on ' . efa_version() . ' ...ERROR INITIALIZATING, CHECK CLAMD... ';" /var/www/html/mailscanner/functions.php
    rm -f /var/run/eFa-Post-Init.lock
    exit 1
  fi
fi

# Fetch the initial public suffix list
curl -s https://publicsuffix.org/list/public_suffix_list.dat > /etc/opendmarc/public_suffix_list.dat
if [[ $? -ne 0 ]]; then
    logger -p user.warn "eFa Post Init: Unable to download the public suffix list!  Please fix me to finish initializing eFa.  Retrying in 1 minute..."
    sed -i "/^    echo ' running on ' . efa_version/ c\    echo ' running on ' . efa_version() . ' ...ERROR INITIALIZATING, CHECK public suffix list... ';" /var/www/html/mailscanner/functions.php
    rm -f /var/run/eFa-Post-Init.lock
    exit 1
fi

systemctl enable opendmarc
systemctl start opendmarc
if [[ $? -ne 0 ]]; then
    logger -p user.warn "eFa Post Init: opendmarc failed to start!  Please fix me to finish initializing eFa.  Retrying in 1 minute..."
    sed -i "/^    echo ' running on ' . efa_version/ c\    echo ' running on ' . efa_version() . ' ...ERROR INITIALIZATING, CHECK opendmarc... ';" /var/www/html/mailscanner/functions.php
    rm -f /var/run/eFa-Post-Init.lock
    exit 1
fi

systemctl enable msmilter
systemctl start msmilter

/usr/bin/mysql -e "ALTER database sqlgrey CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;"

# Schedule eFa-Monitor cron
echo "* * * * * root /usr/sbin/eFa-Monitor-cron >/dev/null 2>&1" > /etc/cron.d/eFa-Monitor.cron

# Remove INITIALIZING message
sed -i "/^    echo ' running on ' . efa_version/ c\    echo ' running on ' . efa_version();" /var/www/html/mailscanner/functions.php

############################## LATE PHASE ###################################
# Tasks that are not needed for email to relay
#############################################################################

# Late Asynchronous tasks
samplepath='spamassassin'
/usr/bin/sa-learn -p /etc/MailScanner/spamassassin.conf --spam --file /usr/share/doc/$samplepath/sample-spam.txt &
/usr/bin/sa-learn -p /etc/MailScanner/spamassassin.conf --ham --file /usr/share/doc/$samplepath/sample-nonspam.txt &
su -l -c "/bin/cat /usr/share/doc/$samplepath/sample-spam.txt | razor-report -d --verbose" -s /bin/bash postfix &
/usr/bin/mailwatch/tools/Cron_jobs/mailwatch_update_sarules.php &

# Late Synchronous tasks
if [[ ! -f /etc/postfix/ssl/dhparam.pem ]]; then
  /usr/bin/openssl dhparam -out /etc/postfix/ssl/dhparam.pem 2048
  /usr/sbin/postconf -e "smtpd_tls_dh1024_param_file = /etc/postfix/ssl/dhparam.pem"
  cat /etc/postfix/ssl/dhparam.pem >> /etc/pki/tls/certs/localhost.crt
fi

# Late Reload daemons
systemctl reload postfix
if [[ $? -ne 0 ]]; then
  # Postfix error!
  logger -p user.warn "eFa Post Init: Postfix reload failed!  Please fix me to finish initializing eFa."
fi
systemctl reload httpd
if [[ $? -ne 0 ]]; then
  # Apache Error!
  logger -p user.warn "eFa Post Init: Apache reload failed!  Please fix me to finish initializing eFa."
fi

# No idea how this bak file is appearing in this directory, just purge it if it is present
rm -f /etc/sysconfig/network-scripts/ifcfg*bak

rm -f /var/run/eFa-Post-Init.lock
rm -f /etc/cron.d/efapostinit

# Kill off parent process to prevent zombie state
kill -9 $PPID

exit 0
