#!/bin/sh

# 定义证书路径
CERT_DIR="/etc/nginx/certs"
CRT_FILE="$CERT_DIR/server.crt"
KEY_FILE="$CERT_DIR/server.key"

# 确保目录存在
mkdir -p "$CERT_DIR"

# 如果证书不存在，生成自签名证书以防止Nginx启动失败
if [ ! -f "$CRT_FILE" ] || [ ! -f "$KEY_FILE" ]; then
    echo "SSL certificates not found. Generating self-signed certificates..."
    openssl req -x509 -nodes -days 365 -newkey rsa:2048 \
        -keyout "$KEY_FILE" \
        -out "$CRT_FILE" \
        -subj "/C=CN/ST=State/L=City/O=Organization/CN=localhost"
    echo "Self-signed certificates generated."
fi

# 启动 Nginx (后台运行)
echo "Starting Nginx..."
nginx -g "daemon on;"

# 启动文件监控循环
echo "Starting SSL certificate monitor..."
while true; do
    # 监控 /etc/nginx/certs 目录下的 modify, move, create, delete 事件
    inotifywait -e modify,move,create,delete -r "$CERT_DIR"
    
    echo "Certificate change detected. Testing configuration..."
    nginx -t
    if [ $? -eq 0 ]; then
        echo "Configuration valid. Reloading Nginx..."
        nginx -s reload
    else
        echo "Configuration invalid. Skipping reload."
    fi
done

