#! /bin/bash
#should probably add logic to only halt/reload once (and only if necessary)
function halt() {
    #stop services if necessary
    if [ -d /var/lib/ipa/ ]
        #stop httpd
        systemctl stop httpd
    fi
}
function reload() {
    #reload/restart relevant services
    if [ -d /etc/nginx/certs/ ]
    then
        systemctl reload nginx
    fi
    if [ -d /var/lib/ipa/ ]
        #restart httpd
        /scripts/setup-le.sh
        systemctl start httpd
        #load cert
    fi

}

dom=`date +%d`
today=`date +%Y%m%d`
log=/var/log/certbot-renewal.log
echo Renewal attempt for $today >> $log
#rotate log file every month
if [[ $dom = 1 ]];then mv $log $log.bak;fi
for f in `ls /etc/letsencrypt/live/ --ignore "README"`
do
    echo Checking $f >> $log
    #check if cert has already expired or will expire within the next two days and renew if applicable
    expires=$(echo `openssl x509 -enddate -noout -in /etc/letsencrypt/live/$f/cert.pem` " - 2 day" | grep -Po "(?<=notAfter=).*" | date +%Y%m%d -f -)
    if [[ $today > $expires ]]
    then
        echo Certificate for $f is expired, renewing >> $log
        halt()
        certbot renew --cert-name $f >> /var/log/certbot-renewal.log
        reload()
        continue
    fi
    #convert hostname into day of month between 0 and 28 to renew on specific day of month (reduce chance of running out of cert renewals)
    hash=$(echo $f| md5sum)
    num=$((0x${hash%% *}))
    for d in {0..2}
    do 
        rdate=$(((${num#-}+$d)%28+1))
        if [[ $dom -eq $rdate ]]
        then
            echo Date falls within renewal window for $f, attempting renewal >> $log
            halt()
            certbot renew --cert-name $f >> $log
            reload()
            break
        fi
    done
done