#!/bin/bash

# Configuration
DOMAINS=("deploy.eatsun.com.cn" "pve.eatsun.com.cn" "openclaw.eatsun.com.cn" "gitlab.eatsun.com.cn")
EMAIL="admin@eatsun.com.cn" # Please update with your email
WEBROOT="/mnt/nfs/deploy/docker/nginx/html"

# Ensure script is run as root
if [ "$EUID" -ne 0 ]; then
  echo "Please run as root"
  exit 1
fi

# Function to check if nginx container is running
is_nginx_running() {
    docker ps --format '{{.Names}}' | grep -q "^nginx-proxy$"
}

# Create webroot directory if it doesn't exist
mkdir -p "$WEBROOT"

for DOMAIN in "${DOMAINS[@]}"; do
    if [ -d "/etc/letsencrypt/live/$DOMAIN" ]; then
        echo "Certificate for $DOMAIN already exists. Skipping."
        continue
    fi

    echo "----------------------------------------------------------------"
    echo "Obtaining certificate for $DOMAIN..."
    echo "----------------------------------------------------------------"

    if is_nginx_running; then
        echo "Nginx (nginx-proxy) is running. Using webroot mode."
        certbot certonly --webroot -w "$WEBROOT" -d "$DOMAIN" --email "$EMAIL" --agree-tos --no-eff-email --non-interactive
    else
        echo "Nginx (nginx-proxy) is NOT running. Using standalone mode."
        # Check if port 80 is bound by something else
        if lsof -Pi :80 -sTCP:LISTEN -t >/dev/null ; then
            echo "Warning: Port 80 is in use by another process. Standalone mode might fail."
        fi
        certbot certonly --standalone -d "$DOMAIN" --email "$EMAIL" --agree-tos --no-eff-email --non-interactive
    fi
done

echo "----------------------------------------------------------------"
echo "Certificate generation process completed."

if is_nginx_running; then
    echo "Reloading Nginx to apply any new certificates..."
    docker exec nginx-proxy nginx -s reload
else
    echo "You can now start the Nginx container with: docker compose up -d"
fi
