#!/usr/bin/env bash
# Let's Encrypt 证书自动续签脚本
# 配合 cron：0 2 * * * /opt/nginx/renew.sh > /var/log/cert-renew.log 2>&1

set -euo pipefail

LOG="[$(date '+%F %T')]"

echo "$LOG ▶ 开始检查证书..."

# 1. 续签（仅在 30 天内即将到期才会真签）
certbot renew --quiet --no-self-upgrade

# 2. 重载 Nginx（不断现有连接）
if pgrep nginx > /dev/null; then
    nginx -t && nginx -s reload
    echo "$LOG ✅ Nginx 已 reload"
else
    echo "$LOG ⚠ Nginx 未运行，跳过 reload"
fi

echo "$LOG ✅ 检查完成"
