#!/bin/bash

### <=================================================================================================> ###
### ---> maintenance = 2019 Version $ Wed Jan 28 13:08:14 am BRST ===============> ###
### 
### <=================================================================================================> ###

/usr/sbin/ntpdate -u pool.ntp.br >> /dev/null 2>&1 || /usr/bin/rdate -s rdate.cpanel.net >> /dev/null 2>&1
/usr/bin/updatedb 

Domain=`cat /root/newtonpmta-scripts/domain.info` 
SendingUser=`cat /root/newtonpmta-scripts/sendinguser.info`
MonitoringEmail=`cat /root/newtonpmta-scripts/monitoringemail.info`
Data=`date`
ManData=`date +%Y_%m_%d`
ManLog="/tmp/manutencao-diaria.log"
ArqBackup="backup-local-$Domain-$ManData.tar.gz"
IpAddr=`cat /root/newtonpmta-scripts/ips.info`
ListaRbl=`cat /root/newtonpmta-scripts/rbl-2015.info`
sqlpass=`cat /root/newtonpmta-scripts/sqlpass.info`

echo "
### <=================================================================================================> ###
Maintenance of the server. $Domain in $Data ...
### <=================================================================================================> ###
" > $ManLog

echo " 
Analysis Ips ...
### <=================================================================================================> ###
" >> $ManLog

for Ip in $IpAddr
do
    echo -n "$Ip = ">> $ManLog
    Teste1=`host $Ip 200.221.11.100 | tail -1 | awk '{ print $5 }'`
    Teste2=`host $Teste1 200.221.11.100 | tail -1 | awk '{ print $4 }'`
        if [ "$Ip" = "$Teste2" ]
        then
            host $Ip 200.221.11.100 | tail -1 | grep $Domain >> /dev/null 2>&1
                if [ $? = 0 ]
                then 
                    echo -n "$Teste1 OK = ">> $ManLog
                else
                    echo -n "Check Reverse $Teste1 = " >> $ManLog
                fi
        else 
            echo -n "Check Reverse $Teste1 = " >> $ManLog
        fi

    Octeto1=`echo "$Ip" | cut -f1 -d"."`
    Octeto2=`echo "$Ip" | cut -f2 -d"."`
    Octeto3=`echo "$Ip" | cut -f3 -d"."`
    Octeto4=`echo "$Ip" | cut -f4 -d"."`

    IpReverseDNS=`echo "$Octeto4.$Octeto3.$Octeto2.$Octeto1"`
    QualidadeIp=`dig $IpReverseDNS.score.senderscore.com @200.221.11.100 | grep ";; ANSWER" -A1 | grep senderscore | cut -d'.' -f11`
    
    ls /root/newtonpmta-scripts/ipspeed.info >> /dev/null 2>&1 
    if [ $? = 0 ]
    then
        VelocidadeIp=`cat /root/newtonpmta-scripts/ipspeed.info`
        grep -o " $Ip " /etc/pmta/config >> /dev/null 2>&1 
        if [ $? = 0 ]
        then
            LinhaVelocidadeIp=$(expr $(grep -n " $Ip " /etc/pmta/config | cut -d: -f1) + 3) 
            sed -i "$LinhaVelocidadeIp s/.*/max-msg-rate $VelocidadeIp\/h/" /etc/pmta/config 
            echo "Quality configured ip $VelocidadeIp/h in $QualidadeIp% ! " >> $ManLog
        else
            echo "Ip of quality $QualidadeIp% ! " >> $ManLog
        fi
    else
        MaximumIPSpeed=`cat /root/newtonpmta-scripts/maximumipspeed.info`
        CalculoVelocidade=`expr $MaximumIPSpeed \* \( $QualidadeIp + 1 \) / 100 2> /dev/null`
        [ $CalculoVelocidade -lt 250 ] && VelocidadeVariavel=250 || VelocidadeVariavel=$CalculoVelocidade
        grep -o " $Ip " /etc/pmta/config >> /dev/null 2>&1 
        if [ $? = 0 ]
        then
            LinhaVelocidadeIp=$(expr $(grep -n " $Ip " /etc/pmta/config | cut -d: -f1) + 3) 
            sed -i "$LinhaVelocidadeIp s/.*/max-msg-rate $VelocidadeVariavel\/h/" /etc/pmta/config 
            echo "Quality of the configured ip $VelocidadeVariavel/h in $QualidadeIp% ! " >> $ManLog
        else
            echo "Quality configured ip in $QualidadeIp% ! " >> $ManLog
        fi
    fi

    for BlackList in $ListaRbl
    do 
        dig $IpReverseDNS.$BlackList @200.221.11.100 |grep ";; ANSWER" >> /dev/null 2>&1
        if [ $? = 0 ]
        then
            dig $IpReverseDNS.$BlackList @200.221.11.100 |grep ";; ANSWER" -A1 |grep "spamhaus" |grep "127.0.1.255" >> /dev/null 2>&1
            if [ $? = 1 ]
            then
                echo "Listed on $BlackList" >> $ManLog
            fi
        fi
    done

    grep $Ip /var/log/pmta/*`date +%Y-%m-%d`*.csv | grep -q 'Cloudmark Poor Reputation Sender Blacklist'
        if [ $? = 0 ] 
        then 
            echo "Listed on CSI-Cloudmark" >> $ManLog
        fi

    grep $Ip /var/log/pmta/*`date +%Y-%m-%d`*.csv | grep -q 'Trend Micro Network Reputation Service' 
        if [ $? = 0 ] 
        then 
            echo "Listed on Trend Micro" >> $ManLog
        fi

echo " 
### <=================================================================================================> ###
" >> $ManLog

done

VelocidadeMaximaInterspire=`grep max-msg-rate /etc/pmta/config | grep -v '#' | cut -d' ' -f2 | cut -d/ -f1 | paste -s -d + | bc`
VelocidadeMaximaPmta=`expr $VelocidadeMaximaInterspire \* 2`
LinhaVelocidadeMaximaPmta=$(grep -n 'Limite de envios do Powermta' /etc/pmta/config | cut -d: -f1) 
sed -i "$LinhaVelocidadeMaximaPmta s/.*/max-msg-rate $VelocidadeMaximaPmta\/h # Limite de envios do Powermta/" /etc/pmta/config

echo "
The maximum speed was set at server $VelocidadeMaximaInterspire emails per hour
### <=================================================================================================> ###
" >> $ManLog


echo "stopping services ... 
### <=================================================================================================> ###
" >> $ManLog

/etc/init.d/crond stop >> /dev/null 2>&1 && /etc/init.d/crond stop >> /dev/null 2>&1
/etc/init.d/pmta stop >> /dev/null 2>&1; sleep 120 && /etc/init.d/pmta stop >> /dev/null 2>&1
/etc/init.d/named stop >> /dev/null 2>&1; sleep 60 && /etc/init.d/named stop >> /dev/null 2>&1
/etc/init.d/postfix stop >> /dev/null 2>&1; sleep 30 && /etc/init.d/postfix stop >> /dev/null 2>&1
/etc/init.d/httpd stop >> /dev/null 2>&1; sleep 15 && /etc/init.d/httpd stop >> /dev/null 2>&1
/etc/init.d/dovecot stop >> /dev/null 2>&1 && /etc/init.d/dovecot stop >> /dev/null 2>&1

echo "Starting process of cleaning and checking of folders and Logs ... 
### <=================================================================================================> ###
" >> $ManLog

rm -rf /backup-local-$Domain
/usr/bin/find /root/newtonpmta-scripts/backup-local/ -type f -mtime +7 -exec rm -rf {} \+ 
/usr/bin/find /var/log/pmta/ -type f -mtime +7 -exec rm -rf {} \+ 
/usr/bin/find /var/spool/pmta/ -type f -mtime +7 -exec rm -rf {} \+ 
> /var/named/chroot/var/named/data/named.run
chown named:named /var/named/chroot/var/named/data/named.run

echo "Maintenance of the mysql ... 
### <=================================================================================================> ###
" >> $ManLog



/usr/bin/mysqlcheck -uroot -p$sqlpass --auto-repair -o mailwizz

echo " 
Creating backup ... 
### <=================================================================================================> ###
" >> $ManLog

mkdir /backup-local-$Domain

cp -Rap /var/www/mw /backup-local-$Domain/mw-$Domain-$ManData
/usr/bin/mysqldump -uroot -p$sqlpass mailwizz --lock-all-tables > /backup-local-$Domain/mailwizz-$Domain-$ManData/dump-mailwizz-$Domain-$ManData.sql

cp -Rap /home/$SendingUser/websites /backup-local-$Domain/websites-$Domain-$ManData
/usr/bin/mysqldump -uroot -p$sqlpass websites --lock-all-tables > /backup-local-$Domain/websites-$Domain-$ManData/dump-web-$Domain-$ManData.sql

tar -zcf /root/newtonpmta-scripts/backup-local/$ArqBackup /backup-local-$Domain
rm -rf /backup-local-$Domain

echo "
Restarting services ... 
### <=================================================================================================> ###
" >> $ManLog

/etc/init.d/pmta start >> /dev/null 2>&1; sleep 120 && /etc/init.d/pmta start >> /dev/null 2>&1
/etc/init.d/named start >> /dev/null 2>&1; sleep 60 && /etc/init.d/named start >> /dev/null 2>&1
/etc/init.d/postfix start >> /dev/null 2>&1; sleep 30 && /etc/init.d/postfix start >> /dev/null 2>&1
/etc/init.d/httpd start >> /dev/null 2>&1; sleep 15 && /etc/init.d/httpd start >> /dev/null 2>&1
/etc/init.d/dovecot start >> /dev/null 2>&1 && /etc/init.d/dovecot start >> /dev/null 2>&1

echo "
Analyze resources ... 
### <=================================================================================================> ###
" >> $ManLog

/bin/sync && /bin/echo 3 > /proc/sys/vm/drop_caches >> /dev/null 2>&1

/etc/init.d/mysqld status >> $ManLog
    if [ $? -ne 0 ]
    then
        /etc/init.d/mysqld restart >> $ManLog
        sleep 30
        /etc/init.d/mysqld status >> $ManLog
            if [ $? -ne 0 ]
            then 
                echo "Error == Mysql down " >> $ManLog
            else
                echo "Error == Mysql restart " >> $ManLog
            fi
    fi

/etc/init.d/httpd status >> $ManLog
    if [ $? -ne 0  ]
    then
        /etc/init.d/httpd restart >> $ManLog
        sleep 30
        /etc/init.d/httpd status >> $ManLog
            if [ $? -ne 0 ]
            then 
                echo "Error = = Apache down " >> $ManLog
            else
                echo "Error == Apache restart " >> $ManLog
            fi
    fi

/etc/init.d/dovecot status  >> $ManLog
    if [ $? -ne 0  ]
    then
        /etc/init.d/dovecot restart >> $ManLog
        sleep 30
        /etc/init.d/dovecot status >> $ManLog
            if [ $? -ne 0 ]
            then
                echo "Error == Dovecot down " >> $ManLog
            else
                echo "Error == Dovecot restart " >> $ManLog
            fi
    fi

/etc/init.d/postfix status >> $ManLog
    if [ $? -ne 0  ]
    then
        /etc/init.d/postfix restart >> $ManLog
        sleep 30
        /etc/init.d/postfix status >> $ManLog
            if [ $? -ne 0 ]
            then 
                echo "Error == Postfix down " >> $ManLog
            else
                echo "Error == Postfix restart " >> $ManLog
            fi
    fi

/etc/init.d/named status >> $ManLog
    if [ $? -ne 0  ]
    then
        /etc/init.d/named restart >> $ManLog
        sleep 30
        /etc/init.d/named status >> $ManLog
            if [ $? -ne 0 ]
            then 
                echo "Error == Named down " >> $ManLog
            else
                echo "Error == Named restart " >> $ManLog
            fi
    fi

ls /var/spool/ |grep pmta >> /dev/null 
    if [ $? -ne 0 ]
    then 
        /etc/init.d/pmta stop >> $ManLog
        mkdir /var/spool/pmta
        chown pmta:pmta /var/spool/pmta
        /etc/init.d/pmta restart >> $ManLog
        sleep 90
        echo "Error ==/var/spool/pmta Folder re-created, pmta restarted " >> $ManLog
    fi

/etc/init.d/pmta status >> $ManLog
    if [ $? -ne 0  ]
    then
        /etc/init.d/pmta restart >> $ManLog
        sleep 90
        /etc/init.d/pmta status >> $ManLog
            if [ $? -ne 0 ]
            then 
                echo "Error == PowerMTA down " >> $ManLog
            else
                echo "Error == PowerMTA restart " >> $ManLog
            fi
    fi

/sbin/service pmtahttp status >> $ManLog
   if [ $? = 0  ]
   then
        /usr/bin/w | grep root >> $ManLog
            if [ $? -ne 0 ]
            then 
                /sbin/service pmtahttp stop >> $ManLog
                echo "Error == PMTA-http restart " >> $ManLog
            fi
    fi

/etc/init.d/crond start >> /dev/null 2>&1 && /etc/init.d/crond start >> /dev/null 2>&1

grep Erro $ManLog >> /dev/null 2>&1
    if [ $? -ne 0 ]
    then    
        echo "
        maintenance Ok ! ( Ok )
### <=================================================================================================> ###
" >> $ManLog
    else
        echo "
        Server failure, Maintenance points. (Error)
### <=================================================================================================> ###
" >> $ManLog
    fi

cat $ManLog >> /var/log/pmta/log
cat $ManLog >> /var/log/messages

Versao=`cut -d" " -f3 /etc/redhat-release | cut -d"." -f1`
    if [ $Versao = 6 ]
    then
        cat $ManLog | mail -r manutencao@server.$Domain -s "Maintenance of the server. $Domain in $Data! " $MonitoringEmail
    else
        cat $ManLog | mail -s "Maintenance of the server. $Domain in $Data! " $MonitoringEmail -- -f manutencao@server.$Domain
    fi

/etc/init.d/crond start >> /dev/null 2>&1 && /etc/init.d/crond start >> /dev/null 2>&1

