#!/bin/bash
#
# Copyright 2016 by S. Piccardi, Trulite Srl
#
# 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; version 2 of the License.
#
# 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 or from the site that you downloaded it
# from; if not, write to the Free Software Foundation, Inc., 59 Temple
# Place, Suite 330, Boston, MA  02111-1307   USA

#
# Cron script to renew Let's Encypt certificates, put it in
# /etc/cron.weekly/ (automatic renewal is done if a certificate is
# expiring in 30 days)
#

# where letsencript is installed (by git cloning repo)
BASE=/root/letsencrypt

# services to be restarted (modify according to your setup)
SERVICES="nginx"

# set logfile
DAY=$(date +%a)
TMPLOG=/tmp/le-renew-$DAY.log
LELOG=$(tempfile -p lernew)

MESS="LE renew on $(hostname) for $(date +%x)"
exec > $TMPLOG 2>&1
echo "$MESS started at $(date +%R)"

if ! cd $BASE; then
    echo unable to find $BASE installation directory
    echo renew failed
else 
    ./letsencrypt-auto renew > $LELOG 2>&1
    if ! grep "No renewals were attempted" $LELOG > /dev/null; then
	for i in $SERVICES; do
	    service $i restart
	done
    fi
    cat $LELOG
    rm -f $LELOG
fi

mailx -s "$MESS results" report@truelite.it < $TMPLOG
