Files
2026-06-25 07:36:25 +02:00

89 lines
3.0 KiB
Bash

#!/bin/sh
set -eu
enabled="${LETSENCRYPT_ENABLED:-0}"
domain="${LETSENCRYPT_DOMAIN:-azionelab.org}"
interval="${TLS_RELOAD_INTERVAL_SECONDS:-30}"
trust_proxy_headers="${TRUST_PROXY_HEADERS:-0}"
certificate="/etc/letsencrypt/live/${domain}/fullchain.pem"
private_key="/etc/letsencrypt/live/${domain}/privkey.pem"
http_config="/etc/nginx/http-enabled/site.conf"
tls_config="/etc/nginx/tls-enabled/site.conf"
tls_template="/etc/nginx/templates/tls.conf.template.source"
base_template="/etc/nginx/templates/default.conf.template.source"
base_config="/etc/nginx/conf.d/default.conf"
proxy_template="/etc/nginx/templates/proxy-routes.conf.template.source"
proxy_routes="/etc/nginx/snippets/proxy-routes.conf"
case "$domain" in
"" | *[!A-Za-z0-9.-]* | .* | *. | *..* | -* | *- | *.-* | *-.*)
echo "Invalid LETSENCRYPT_DOMAIN: $domain" >&2
exit 1
;;
esac
case "$domain" in *.*) ;; *) echo "LETSENCRYPT_DOMAIN must be a fully qualified domain name." >&2; exit 1 ;; esac
case "$enabled" in 0 | 1) ;; *) echo "LETSENCRYPT_ENABLED must be 0 or 1." >&2; exit 1 ;; esac
case "$trust_proxy_headers" in
0) forwarded_for='$remote_addr'; forwarded_proto='$scheme' ;;
1) forwarded_for='$proxy_add_x_forwarded_for'; forwarded_proto='$effective_forwarded_proto' ;;
*) echo "TRUST_PROXY_HEADERS must be 0 or 1." >&2; exit 1 ;;
esac
case "$interval" in "" | *[!0-9]*) echo "TLS_RELOAD_INTERVAL_SECONDS must be a positive integer." >&2; exit 1 ;; esac
[ "$interval" -gt 0 ] || { echo "TLS_RELOAD_INTERVAL_SECONDS must be positive." >&2; exit 1; }
certificate_state() {
if [ ! -s "$certificate" ] || [ ! -s "$private_key" ]; then
echo missing
return
fi
cksum "$certificate" "$private_key" | cksum | awk '{print $1 ":" $2}'
}
render_http() {
printf 'include %s;\n' "$proxy_routes" > "$http_config"
rm -f "$tls_config"
}
render_pending() {
cat > "$http_config" <<'EOF'
location / {
add_header Retry-After "60" always;
return 503;
}
EOF
rm -f "$tls_config"
}
render_https() {
sed "s|__DOMAIN__|${domain}|g" "$tls_template" > "${tls_config}.tmp"
mv "${tls_config}.tmp" "$tls_config"
printf 'location ^~ / { return 301 https://$host$request_uri; }\n' > "$http_config"
}
sed -e "s|__X_FORWARDED_FOR__|${forwarded_for}|g" -e "s|__X_FORWARDED_PROTO__|${forwarded_proto}|g" "$proxy_template" > "${proxy_routes}.tmp"
mv "${proxy_routes}.tmp" "$proxy_routes"
sed "s|__DOMAIN__|${domain}|g" "$base_template" > "${base_config}.tmp"
mv "${base_config}.tmp" "$base_config"
if [ "$enabled" = 0 ]; then
render_http
exit 0
fi
state="$(certificate_state)"
if [ "$state" = missing ]; then render_pending; else render_https; fi
(
while sleep "$interval"; do
next_state="$(certificate_state)"
[ "$next_state" = "$state" ] && continue
if [ "$next_state" = missing ]; then render_pending; else render_https; fi
if nginx -t; then
nginx -s reload
state="$next_state"
else
echo "TLS configuration reload failed; retrying after ${interval}s." >&2
fi
done
) &