#!/bin/bash

PSAUX=`ps aux | grep letsencrypt | grep -v grep`
if [ ! -z "$PSAUX" ]; then
    echo "letsencrypt is currently in use"
    exit;
fi

LE=$(which letsencrypt)
# prefer newer version from git
if [ -f "/root/letsencrypt/letsencrypt-auto" ]; then
    LE='/root/letsencrypt/letsencrypt-auto'
fi
if [ -f "/root/certbot/letsencrypt-auto" ]; then
    LE='/root/certbot/letsencrypt-auto'
fi

if [ ! -d "/etc/letsencrypt/live/" ]; then
    echo "no cert found"
    exit;
fi

if [ -r /etc/default/letsrenew ]; then
    . /etc/default/letsrenew
fi

for domainpath in /etc/letsencrypt/live/*.*; do

    DOMAIN=`basename $domainpath`

    DATE=`openssl x509 -enddate -noout -in /etc/letsencrypt/live/${DOMAIN}/cert.pem | sed s/'notAfter='//g`
    TIMESTAMP=`date -d "$DATE" "+%s"`
    TIMESTAMP=`expr $TIMESTAMP - 2678400`
    CURTIMESTAMP=`TZ=GMT date "+%s"`

    # okay an simple force method, if something went wrong :)
    if [ "$1" == "--force" ]; then
        echo "force"
        TIMESTAMP=0
    fi

    if test $TIMESTAMP -lt $CURTIMESTAMP; then

        # stop service
        if [ -f /etc/init.d/nginx ]; then
            /etc/init.d/nginx stop
        fi
        if [ -f /etc/init.d/apache2 ]; then
            /etc/init.d/apache2 stop
        fi

        echo "renew ${DOMAIN}"
        $LE renew --force-renew --manual-public-ip-logging-ok

        # start service
        if [ -f /etc/init.d/nginx ]; then
            /etc/init.d/nginx restart
        fi
        if [ -f /etc/init.d/apache2 ]; then
            /etc/init.d/apache2 restart
        fi

        echo $DOMAIN
        echo "expire date: ${TIMESTAMP}"
        echo "cert has been build"
        if [ "$1" == "--force" ]; then
            exit;
        fi
    else
        echo '### NO ###'
        echo $DOMAIN
        echo "expire date: ${TIMESTAMP}"
        date
        echo "nothing todo"
    fi
done
