NgixProxy_Pathfinder/scripts/renew_ssl.sh

77 lines
2.9 KiB
Bash

#!/bin/sh
# SSL Renewal Script
# Checks expiry and attempts renewal if < 3 days
echo "[SSL-Renew] Starting check at $(date)..."
# Ensure ACME snippet is present (idempotent)
/scripts/inject_acme.sh
# Iterate configs to find certs
for conf in /etc/nginx/conf.d/*.conf; do
[ -e "$conf" ] || continue
# Extract Cert File
CRT_FILE=$(grep -E "\s*ssl_certificate\s+" "$conf" | sed -r 's/.*ssl_certificate\s+(.*);/\1/' | head -n 1)
# Extract Server Name for Certbot
DOMAIN=$(grep -E "\s*server_name\s+" "$conf" | sed -r 's/.*server_name\s+(.*);/\1/' | head -n 1)
if [ -f "$CRT_FILE" ]; then
EXPIRY_DATE=$(openssl x509 -in "$CRT_FILE" -noout -enddate | cut -d= -f2)
EXPIRY_EPOCH=$(date -d "$EXPIRY_DATE" +%s)
CURRENT_EPOCH=$(date +%s)
DAYS_LEFT=$(( ($EXPIRY_EPOCH - $CURRENT_EPOCH) / 86400 ))
if [ "$DAYS_LEFT" -le 3 ]; then
echo "[SSL-Renew] WARNING: Cert for $DOMAIN expires in $DAYS_LEFT days!"
echo "[SSL-Renew] Attempting renewal via Certbot..."
# Attempt non-interactive renewal
# If certbot doesn't know this cert yet, register it
# --webroot-path matches snippets/acme_challenge.conf
certbot certonly --webroot -w /var/www/certbot \
-d "$DOMAIN" \
--email suporte@itguys.com.br \
--agree-tos \
--no-eff-email \
--non-interactive \
--keep-until-expiring
if [ $? -eq 0 ]; then
echo "[SSL-Renew] Certbot success. Updating symlinks/files..."
# Here we have a drift: current config points to /etc/nginx/ssl/file.pem
# Certbot puts it in /etc/letsencrypt/live/domain/fullchain.pem
# We need to update the file used by NGINX or basic copy
LE_CERT="/etc/letsencrypt/live/$DOMAIN/fullchain.pem"
LE_KEY="/etc/letsencrypt/live/$DOMAIN/privkey.pem"
if [ -f "$LE_CERT" ]; then
cp "$LE_CERT" "$CRT_FILE"
# Key file assumption: usually same name but .key/privkey.pem
# We extract the key path from config to be safe
KEY_FILE=$(grep -E "\s*ssl_certificate_key\s+" "$conf" | sed -r 's/.*ssl_certificate_key\s+(.*);/\1/' | head -n 1)
if [ -f "$KEY_FILE" ]; then
cp "$LE_KEY" "$KEY_FILE"
fi
echo "[SSL-Renew] Files updated. Queuing NGINX reload."
RELOAD_NEEDED=1
fi
else
echo "[SSL-Renew] Certbot failed for $DOMAIN."
fi
fi
fi
done
if [ "$RELOAD_NEEDED" = "1" ]; then
echo "[SSL-Renew] Reloading NGINX..."
nginx -s reload
fi
echo "[SSL-Renew] Check complete."