#!/bin/bash
# Renew Let's Encrypt SSL cert

kyrfile=/local/notesdata/keyring2.kyr
pathtocerts=/etc/letsencrypt/live/www.gwbasics.be

cd /root
./certbot-auto renew

if [ $? -ne 0 ]
	then 
		./certbot-auto renew --pre-hook "su - notes -c \"/opt/ibm/domino/bin/server -c 'tell http quit'\""
	else
		exit 0
fi
if [ $? -ne 0 ]
 then
        ERRORLOG=`tail /var/log/letsencrypt/letsencrypt.log`
        echo -e "The Lets Encrypt Cert has not been renewed! \n \n" $ERRORLOG
	 
 else
	echo "copy certs to /tmp"
	cp $pathtocerts/cert.pem /tmp/cert.pem
	cp $pathtocerts/fullchain.pem /tmp/fullchain.pem
	cp $pathtocerts/privkey.pem /tmp/privkey.pem
	echo "import certs"	
	su - notes -c "/opt/ibm/domino/bin/tools/startup kyrtool =/local/notesdata/notes.ini import roots -k $kyrfile -i /tmp/fullchain.pem"
	su - notes -c "/opt/ibm/domino/bin/tools/startup kyrtool =/local/notesdata/notes.ini import keys -k  $kyrfile -i /tmp/privkey.pem"
	su - notes -c "/opt/ibm/domino/bin/tools/startup kyrtool =/local/notesdata/notes.ini import certs -k $kyrfile -i /tmp/cert.pem"
	rm /tmp/cert.pem
	rm /tmp/fullchain.pem
	rm /tmp/privkey.pem      
	#restart domino
	echo "start http server"
fi

su - notes -c "/opt/ibm/domino/bin/server -c 'load http'"

exit 0

