shell-scripts/my-le-renew.sh
c47 8acec8b7fc Add my-le-renew.sh
A wrapper script for the 'dehydrated' letsencrypt
client.
2023-10-30 19:15:29 +01:00

145 lines
3.8 KiB
Bash

#!/bin/bash
#
# This is a modified version of a script originally developed by
# Felix Tiede. It is a wrapper script for dehydrated to renew
# LetsEncrypt certificates on my servers.
# set exit on error
set -e
LEDIR=
wget -O - https://letsencrypt.org/certs/lets-encrypt-x3-cross-signed.pem > ${LEDIR}/intermediate.pem 2>/dev/null
HOSTS=`cd ${LEDIR}; ls -d */ | sed 's/\/\+$//'`
function help() {
echo
echo -e "\tUsage:"
echo -e "\tlerenew.sh (OPTIONS) (HOSTNAME)"
echo
echo -e "\t-a, --all\t:\tRenewal of all hosts"
echo -e "\t-h, --help\t:\tPrint this help"
echo -e "\tHOSTNAME\t:\tRenewal of provided host"
echo
}
function hasCSR() {
[[ ! -f ${LEDIR}/${HOST}/${HOST}.csr ]] && {
echo 1
} || {
echo 0
}
}
function backupCerts() {
[[ -z ${HOST} ]] && {
echo 1
} || {
local CERTDIR=/etc/ssl/nginx/${HOST}.crt
for file in ${CERTDIR}/*.crt; do
cp ${file} ${file}.bak
done
echo 0
}
}
# This is a general function to perform certificate renewal.
function renewHost() {
[[ -z ${HOST} ]] && {
echo "\${HOST} not set!! Exiting."
exit 1
} || {
local CERTDIR=/etc/ssl/nginx/${HOST}.crt
local DIR=${LEDIR}/${HOST}
local CSR=${DIR}/${HOST}.csr
local CONF=${DIR}/config
local BACKUP=`backupCerts`
[[ ${BACKUP} -eq 0 ]] && {
echo "Certificate backups for host ${HOST} in ${CERTDIR} -> .bak"
echo "Start renewal"
su - -c "/usr/bin/dehydrated \
--signcsr ${CSR} \
--config ${CONF} \
-p ${DIR}/accounts/*/account_key.pem \
-4 \
-t http-01 > ${DIR}/${HOST}.signed.crt" dehydrated
[[ $? -eq 0 ]] && {
#cat ${DIR}/${VHOST}.signed.crt ${LEDIR}/intermediate.pem > ${DIR}/${HOST}.crt
cp ${DIR}/${HOST}.signed.crt ${CERTDIR}/${HOST}.crt
} || {
echo "Something went wrong"
exit 1
}
} || {
echo "Could not backup certificates of host ${HOST}!! Exiting."
exit 1
}
}
}
function singleRenewal() {
# Test if .csr exists
# Path exists (inherently) if .csr exists
local CSR=`hasCSR`
# Initiate certificate renewal or exit if .csr
# file does not exist.
[[ ${CSR} -eq 0 ]] && {
# Call newHost function to renew certificate
# of this single host
renewHost ${HOST}
} || {
# Exit if path or file is missing
echo -e "\n\t${LEDIR}/${HOST}/${HOST}.csr doesn't exist.\n"
exit 1
}
}
#
# Main script flow control
#
# If options -a, --all provided then call function
# to renew all configured hosts.
if [[ ${1} == '-a' ]] || [[ ${1} == '--all' ]]; then
echo ALL
# If options -h, --help provided then call help function
elif [[ ${1} == '-h' ]] || [[ ${1} == '--help' ]]; then
help
# If an FQDN is provided check it's pattern and call
# singleRenewal function if matches.
elif [[ `grep '^[0-9a-z]\+\.nixre.net$' <(echo ${1})` ]]; then
HOST=${1}
singleRenewal ${HOST}
# Else call help function and exit with 1
else
help
exit 1
fi