#!/bin/bash

PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/afribin:/usr/local/bin

find /root/ -maxdepth 1 -name \*hourly\*cron\*begin -exec rm -f {} \; > /dev/null 2>&1
touch /root/.afri_hourly_cron_$(date +%Y%m%d_%H%M%S).begin > /dev/null 2>&1


/usr/local/afribin/maintenance/afriddoswhitelist > /dev/null 2>&1
# stop r1soft from getting killed by oom....
/usr/local/afribin/r1soft/r1soft_oom_disable > /dev/null 2>&1


if [ -d /usr/local/cpanel ]; then

touch /var/log/exim_phishing_filter.log > /dev/null 2>&1
chown cpaneleximfilter:mail /var/log/exim_phishing_filter.log > /dev/null 2>&1
chmod 660  /var/log/exim_phishing_filter.log > /dev/null 2>&1

# Need this for emailOnly migrations - Ryan
/usr/sbin/whmapi1 --output=json listaccts > /root/.listaccts.json

# add afrihost audit rules
#if ! [ -f /etc/audit/rules.d/afrihost.rules ] ; then 
# cat /usr/local/afribin/configs/cpanel_auditd_afrihost.rules >  /etc/audit/rules.d/afrihost.rules > /dev/null 2>&1
#fi

# make sure pureftps ports coincide with our firewall set ports
ps uawfx | grep  pure-ftpd > /dev/null 2>&1 && if ! grep 32760 /etc/pure-ftpd.conf ; then        
 sed -i 's/^PassivePortRange.*/PassivePortRange 30000 32760/g' /etc/pure-ftpd.conf
 service pure-ftpd restart 
fi > /dev/null 2>&1

if ! ls -ald  /home | grep "drwx--x--x" ; then chmod 711 /home ; fi > /dev/null 2>&1

# sqmail horde roundcube - 1=diabled 0=enabled 

# adding force 2fa feature enabled
whmapi1 --output=jsonpretty twofactorauth_policy_status | grep -q '"is_enabled" : "0"' > /dev/null 2>&1  && whmapi1 --output=jsonpretty  twofactorauth_enable_policy > /dev/null 2>&1
whmapi1 set_tweaksetting key=smtpmailgidonly value=0  > /dev/null 2>&1

if egrep -q 'skipsqmail=1|skiphorde=1|skiproundcube=1'  /var/cpanel/cpanel.config ; then 
 whmapi1 set_tweaksetting key=skipsqmail value=0 > /dev/null 2>&1
 whmapi1 set_tweaksetting key=skiphorde value=0 > /dev/null 2>&1
 whmapi1 set_tweaksetting key=skiproundcube value=0 > /dev/null 2>&1
fi
whmapi1 set_tweaksetting key=skipdiskcheck value=0 > /dev/null 2>&1
whmapi1 set_tweaksetting key=database_prefix value=1 > /dev/null 2>&1
whmapi1 set_tweaksetting key=skipboxcheck value=0 > /dev/null 2>&1

       # if hostname |grep -q aserv.co.za ; then
       #         #curl -s -o /etc/exim_deny_spe_sender https://spefilter.awsum.co/exim_deny_spe_sender
       #         curl -s -o /etc/exim_deny_spe_sender https://spefilter.awsum.co/exim_deny_spe_sender
#      #         sed -i  '/'$(hostname)'/!d' /etc/exim_deny_spe_sender
       #		if [ -f /etc/exim_whitelistsender ] ; then
       #         	cat /etc/exim_whitelistsender | xargs -i sed -i '/{}/d' /etc/exim_deny_spe_sender
       #		fi
       # fi


tty -s || exec > /var/log/afribin.hourly 2>&1
[ -f /var/log/afribin.hourly ] && chmod 600 /var/log/afribin.hourly

# Stop strace after 30 to 90 minutes
#if find /usr/local/cpanel/cgi-sys/php5 -mmin +30 | grep -q . ; then frob strace ; fi

# Don't let the firewall go away ...
/usr/local/afribin/maintenance/firewall check

/usr/local/afribin/maintenance/senderstats_lockout_multiple_ip_auth  --lockout

# It turns out that these are not jumbo packets on the network:
# /usr/local/afribin/fix_tcp_segmentation_offload_fail

# backupjob_check
/usr/local/afribin/srv_reports/checks/backupjob_check.sh  > /dev/null 2>&1
#scrtipt to get highest spam sent by user
/usr/local/afribin/maintenance/check_highest_spam_by_user  > /dev/null 2>&1
# srvrep install
#/usr/local/afribin/srv_reports/srvrep_client_install.sh > /dev/null 2>&1
# srvrep get job complete check
/usr/local/afribin/srv_reports/checks/r1soft_jobCompleteCheck.sh  > /dev/null 2>&1
# r1soft snap removal error check
/usr/local/afribin/srv_reports/checks/r1soft_snapremovalerror.sh  > /dev/null 2>&1


# repair any corrupt mysql (needs date format update depending on mysql version)
#/usr/local/afribin/maintenance/mysql_table_repair > /dev/null 2>&1

# truncate error logs due to php depercation
time { find /home/*/logs  -name \*.php.error.log  -size +10000k -exec echo "cat /dev/null > "{}"" \;  | bash ; } > /dev/null 2>&1

#Experimental, trying without
#echo -e '<?\n  header("HTTP/1.1 301 Moved Permanently");\n  header("Location: http://www.afrihost.com/index.php"); \n?>' > /usr/local/apache/htdocs/index.php 

# Write a HTML index page
htmlindexpage() {

    URL="$1"
    REDIRECTTIME="$2"
    [ "$URL" ] || return
    [ "$REDIRECTTIME" ] || return

    if [ "$URL" = "http://www.afrihost.com/index.php" ] ; then 
    cat /usr/local/afribin/branding/redirecting.html
    else

    cat << EOF
<html>
<head>
<title>Redirecting...</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<META HTTP-EQUIV="refresh" CONTENT="$REDIRECTTIME;URL=$URL">
</body>
</html>
EOF

    fi

}

# Rewrite index page for our own pages
indexpage() {
    if [ -f /etc/clientspec ] ; then
        exit
    fi
    if [ -f /etc/internetsolutions ] ; then  #An Internet Solutuions box
        redstring='<? header("Location: http://www.is.co.za/"); ?>'
        URL='http://www.is.co.za/'
	REDIRECTTIME='0'
    else
        redstring='<?  header("Location: http://www.afrihost.com/index.php"); ?>'
        URL='http://www.afrihost.com/index.php'
	REDIRECTTIME='1'
    fi
	    
    # For Newsprout server	
    if [ -f /etc/newsprout ] ; then
        redstring='<? header("Location: http://www.newsprout.com.au/"); ?>'
        URL='http://www.newsprout.com.au/'
	REDIRECTTIME='0'
	htmlindexpage $URL $REDIRECTTIME> /usr/local/apache/htdocs/index.html
    fi	

#    if ! grep -qF "$URL" /usr/local/apache/htdocs/index.php 2>/dev/null && \
#       ! grep -qF "$URL" /usr/local/apache/htdocs/index.html 2>/dev/null ; then
#        # Write default index page
#        rm -f /usr/local/apache/htdocs/index.html*
#        echo "$redstring" > /usr/local/apache/htdocs/index.php
#        htmlindexpage $URL $REDIRECTTIME> /usr/local/apache/htdocs/index.html
#    fi
    
#    if ! [[ -s /usr/local/apache/htdocs/index.html ]] ; then 
#	rm -f /usr/local/apache/htdocs/index.html*
#	echo "$redstring" > /usr/local/apache/htdocs/index.php
#	htmlindexpage $URL $REDIRECTTIME> /usr/local/apache/htdocs/index.html
#    fi

#    if cat /usr/local/apache/htdocs/index.html |md5sum |grep -q 3a81d311247086324bc4e23a6e9700b6 ; then 
#	rm -f /usr/local/apache/htdocs/index.html*
#	echo "$redstring" > /usr/local/apache/htdocs/index.php
#	htmlindexpage $URL $REDIRECTTIME> /usr/local/apache/htdocs/index.html
#    fi

    if hostname |grep -q aserv.co.za ; then
    	cat /usr/local/afribin/branding/redirecting.html > /usr/local/apache/htdocs/index.html
    fi
    
    if grep '^AddHandler fcgid-script .*\.php' /usr/local/apache/conf/php.conf >& /dev/null &&
       grep '^Include "/usr/local/apache/conf/php.conf"' /etc/httpd/conf/httpd.conf >& /dev/null ; then
       rm -f /usr/local/apache/htdocs/index.php
    fi

} 


# Set default index page in /usr/local/apache/htdocs
indexpage

# Kill long-running processes
/usr/local/afribin/maintenance/killroundcube100.py

# AARGH: FIXME! 
# This is a temporary fix 2009/10/23 for a BSD clam 0.95.2 death problem
#[ -f /clamd.core ] && rm /clamd.core && /scripts/restartsrv_clamd

# Set Error log perms
if hostname |grep -q aserv.co.za ; then
chmod 640 /usr/local/apache/logs/error_log
chgrp nobody /usr/local/apache/logs/error_log
/usr/local/afribin/configs/spe_ips_trusted_set
fi


# Workaround for cpanel bug where it allows a domain to be in localdomains AND
# remote domains, and then erattically removes it from localdomains.  (when
# /scripts/mailperm is run).  The workaround is that we periodically remove it
# from remotedomains, and preempt the surprise that cpanel has prepared for us.
/usr/local/afribin/maintenance/localdomains-not-remote.py > /dev/null 2>&1

# fix apache includes on Afrihost shared hosting servers. By Ryan
#/usr/local/afribin/maintenance/apache_includes

# Patch /script/suspendacct. By Ryan
/usr/local/afribin/maintenance/patch_suspendacct

# Autosuspend spammers on new boxen
#if find /etc/wwwacct.conf -mtime -90 | grep -q . ; then
# Make that on all boxes for all time:
/usr/local/afribin/maintenance/autosuspendspammers.py 
#fi

# SCRIPTS THAT DO NOT RUN WHEN THE LOAD IS HIGH FOLLOW:

# Check that the load is too high
if [ -f /proc/loadavg ] ; then
    read LOAD MORE < /proc/loadavg
    if [ ${LOAD/.*/} -ge 15 ] ; then
        exit 1  # load too high - don't bother with this other stuff right now:
    fi
fi

# Check for people that keep on downloading the same mail, and lock their
# email accounts by quietly changing the password.
if [ ! -f /etc/reportpop3usage.disabled ] ; then
        find 2>/dev/null /var/log/reportpop3usage.out -type f -size +1000k -exec rm -f {} \;
        /usr/local/afribin/maintenance/reportpop3usage.py --findloop /var/log/maillog >> /var/log/reportpop3usage.out 2>&1
fi

#Fix user permissions
/usr/local/afribin/fixscripts/fixmailpermissions > /dev/null 2> /dev/null

#Wipe frozen messages
/usr/local/afribin/freezewipe --days=1 --silent 2> /dev/null > /dev/null

#Wipe domain_user@ip
#/usr/local/afribin/maintenance/remove_domuser_mail.sh 2> /dev/null > /dev/null

# Test and restart cdp-agent if dead.
if [  -f 'service cdp-agent' ] ; then
        if ! pidof cdp ; then
                service cdp-agent restart
        fi
fi

# Observer test
# /usr/local/afribin/ryan-scripts/observer

# Remove accumulation of fcgi sockets:
#find /usr/local/apache/logs/fcgidsock -mtime +1 -type s -print0|xargs -0 rm
#find /usr/local/apache/logs/fcgidsock/ -mmin +360 -exec rm -fv {} \;

# disbling now because paper_lantern in play -p
#if hostname |grep -v reseller | grep -q aserv.co.za  ; then 
#        /usr/local/afribin/maintenance/fix_afrihost_to_x3
#fi

# making sure no one whitelists the servers IPs as causes ipsets to not block anything.
for i in $(ifconfig   | awk '{print $2}' | ipgrep ) ; do 
        for p in $(ipset list -t | grep Name | grep white | grep -v i360 | awk '{print $NF}') ; do 
              ipset -q del $p $i ; echo "sed -i '/$i/d' /etc/ipwhitelist.ini"|bash 
        done 
done

# making sure sitebuilder is set to afrihost server and not eu server.
if [ -f /usr/local/sitepad/universal.php ] ; then 
        if ! grep "sitebuilder\.afrihost.com" /usr/local/sitepad/universal.php ; then
         sed -i "s#.*host_sm.*#\$globals['host_sm'] \= 'https://sitebuilder.afrihost.com';#" /usr/local/sitepad/universal.php > /dev/null 2>&1
        fi
fi

fi

# Set this sudo as sudo does not maintain PATH for root
if [ ! -e "/usr/bin/frob" ] ; then
        ln -s /usr/local/afribin/frob /usr/bin/frob
fi

if [ ! -e "/usr/bin/su_domain" ] ; then
        ln -s /usr/local/afribin/su_domain /usr/bin/su_domain
fi

if [ ! -e "/usr/bin/checkipblock" ] ; then
        ln -s /usr/local/afribin/checkipblock /usr/bin/checkipblock
fi

if [ ! -e "/bin/url" ] ; then 
        ln -s /usr/local/afribin/url /bin/url 
fi

if ! [ -f /etc/blocked_incoming_email_domains ] ; then touch /etc/blocked_incoming_email_domains ; chown root:mail /etc/blocked_incoming_email_domains ; fi 

find /root/ -maxdepth 1 -name \*hourly\*cron\*end -exec rm -f {} \; > /dev/null 2>&1
touch /root/.afri_hourly_cron_$(date +%Y%m%d_%H%M%S).end > /dev/null 2>&1

# This is temporary until we move these checks into its own cron - Ryan
#/usr/local/afribin/maintenance/node_exporter/cpanel_node_text_exporter
