for file in key.pem cert.pem chain.pem fullchain.pem; do if [ ! -s "$staging/$file" ]; then echo"Missing or empty certificate file: $file" >&2 return 1 fi done
if ! openssl pkey \
-in"$staging/key.pem" \
-noout then echo"Unable to parse key.pem" >&2 return 1 fi
for file in cert.pem chain.pem fullchain.pem; do if ! openssl x509 \
-in"$staging/$file" \
-noout then echo"Unable to parse $file" >&2 return 1 fi done
if ! openssl x509 \
-in"$staging/cert.pem" \
-noout \
-checkend 86400 then echo"Downloaded certificate expires in less than 24 hours" >&2 return 1 fi
if ! cmp -s \ "$validation/cert.der" \ "$validation/fullchain-leaf.der" then echo"cert.pem does not match the leaf certificate in fullchain.pem" >&2 return 1 fi
if ! cmp -s \ "$validation/key-public.der" \ "$validation/cert-public.der" then echo"Downloaded private key does not match the certificate" >&2 return 1 fi
}
downloadSucceeded=false
for attempt in 1 2 3; do echo"Download and validation attempt $attempt/3"
if download_and_validate; then
downloadSucceeded=true break fi
if [ "$attempt" -lt 3 ]; then echo"Download or validation failed; retrying in 15 seconds..." >&2 sleep 15 fi done
if [ "$downloadSucceeded" != true ]; then echo"Unable to download a complete and valid certificate set" >&2 exit 1 fi
unchanged=true
for file in key.pem cert.pem chain.pem fullchain.pem; do if \
[ ! -s "$active/$file" ] \
|| ! cmp -s "$active/$file""$staging/$file" then
unchanged=false break fi done
if [ "$unchanged" = true ]; then echo"Certificate files are unchanged" exit 0 fi
set -euo pipefail
rclone \
--config=/etc/rclone.conf \
--contimeout=30s \
--timeout=2m \
--retries=5 \
--low-level-retries=10 \
--retries-sleep=15s \
copy "r2:tls" new for file in chain.pem fullchain.pem full.pem key.pem; do if [ ! -s "new/$file" ]; then echo"Missing or empty certificate file: $file" >&2 rm -rf new exit 1 fi done
mkdir -p /var/lib/acme/generations
gen="/var/lib/acme/generations/$(sha256sum new/full.pem | cut -d ' ' -f 1)" if [ -d "$gen" ]; then rm -rf new else mv new "$gen" ln -sfT "$gen""/var/lib/acme/${cert}" for g in /var/lib/acme/generations/*; do
[ -e "$g" ] || continue
[ "$g" = "$gen" ] || rm -rf -- "$g" done fi
echo"Certificate for ${cert} updated successfully"