#!/usr/bin/env bash
# Set up Let's Encrypt certificate using DNS-01 challenge for RPC-01 (VMID 2500)
# This is useful when port 80 is not accessible or for internal domains
# Usage: ./setup-letsencrypt-dns-01-rpc-2500.sh <domain> [cloudflare-api-token]

set -e

VMID=2500
PROXMOX_HOST="192.168.11.10"

if [ $# -lt 1 ]; then
    echo "Usage: $0 <domain> [cloudflare-api-token]"
    echo "Example: $0 rpc-core.yourdomain.com YOUR_CLOUDFLARE_API_TOKEN"
    exit 1
fi

DOMAIN="$1"
API_TOKEN="${2:-}"

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

log_info() { echo -e "${BLUE}[INFO]${NC} $1"; }
log_success() { echo -e "${GREEN}[✓]${NC} $1"; }
log_warn() { echo -e "${YELLOW}[WARN]${NC} $1"; }
log_error() { echo -e "${RED}[ERROR]${NC} $1"; }

log_info "Setting up Let's Encrypt certificate (DNS-01) for RPC-01 (VMID $VMID)"
log_info "Domain: $DOMAIN"
echo ""

# Check if domain is .local
if echo "$DOMAIN" | grep -q "\.local$"; then
    log_error "Let's Encrypt does not support .local domains"
    log_info "Please use a public domain (e.g., rpc-core.yourdomain.com)"
    exit 1
fi

# Install Certbot
log_info "1. Installing Certbot..."
if ! sshpass -p 'L@kers2010' ssh -o StrictHostKeyChecking=no root@${PROXMOX_HOST} \
    "pct exec $VMID -- which certbot >/dev/null 2>&1"; then
    sshpass -p 'L@kers2010' ssh -o StrictHostKeyChecking=no root@${PROXMOX_HOST} \
        "pct exec $VMID -- bash -c '
            export DEBIAN_FRONTEND=noninteractive
            apt-get update -qq
            apt-get install -y -qq certbot
        '"
    log_success "Certbot installed"
else
    log_success "Certbot already installed"
fi

# Check if Cloudflare API token provided
if [ -n "$API_TOKEN" ]; then
    log_info ""
    log_info "2. Setting up Cloudflare DNS plugin..."
    
    # Install Cloudflare plugin
    sshpass -p 'L@kers2010' ssh -o StrictHostKeyChecking=no root@${PROXMOX_HOST} \
        "pct exec $VMID -- bash -c '
            export DEBIAN_FRONTEND=noninteractive
            apt-get install -y -qq python3-certbot-dns-cloudflare python3-pip
            pip3 install -q cloudflare 2>/dev/null || true
        '"
    
    # Create credentials file
    log_info "Creating Cloudflare credentials file..."
    sshpass -p 'L@kers2010' ssh -o StrictHostKeyChecking=no root@${PROXMOX_HOST} \
        "pct exec $VMID -- bash -c '
            mkdir -p /etc/cloudflare
            cat > /etc/cloudflare/credentials.ini <<EOF
dns_cloudflare_api_token = $API_TOKEN
EOF
            chmod 600 /etc/cloudflare/credentials.ini
        '"
    
    log_success "Cloudflare credentials configured"
    
    # Obtain certificate using DNS-01
    log_info ""
    log_info "3. Obtaining certificate using DNS-01 challenge..."
    log_warn "This will use Let's Encrypt staging server for testing"
    log_info "Press Ctrl+C to cancel, or wait 5 seconds..."
    sleep 5
    
    CERTBOT_OUTPUT=$(sshpass -p 'L@kers2010' ssh -o StrictHostKeyChecking=no root@${PROXMOX_HOST} \
        "pct exec $VMID -- certbot certonly \
            --dns-cloudflare \
            --dns-cloudflare-credentials /etc/cloudflare/credentials.ini \
            --non-interactive \
            --agree-tos \
            --staging \
            --email admin@$(echo $DOMAIN | cut -d. -f2-) \
            -d $DOMAIN 2>&1" || echo "FAILED")
    
    if echo "$CERTBOT_OUTPUT" | grep -q "Successfully received certificate\|Congratulations"; then
        log_success "Certificate obtained successfully (STAGING)"
        log_warn "To get production certificate, run without --staging flag"
    else
        log_error "Certificate acquisition failed"
        log_info "Output: $CERTBOT_OUTPUT"
        exit 1
    fi
else
    log_info ""
    log_info "2. Manual DNS-01 challenge setup..."
    log_info "No Cloudflare API token provided. Using manual DNS challenge."
    log_info ""
    log_info "Run this command and follow the prompts:"
    log_info "  pct exec $VMID -- certbot certonly --manual --preferred-challenges dns -d $DOMAIN"
    log_info ""
    log_info "You will need to:"
    log_info "  1. Add a TXT record to your DNS"
    log_info "  2. Wait for DNS propagation"
    log_info "  3. Press Enter to continue"
    exit 0
fi

# Update Nginx configuration
log_info ""
log_info "4. Updating Nginx configuration..."
CERT_PATH="/etc/letsencrypt/live/$DOMAIN/fullchain.pem"
KEY_PATH="/etc/letsencrypt/live/$DOMAIN/privkey.pem"

sshpass -p 'L@kers2010' ssh -o StrictHostKeyChecking=no root@${PROXMOX_HOST} \
    "pct exec $VMID -- bash" <<UPDATE_NGINX
# Update SSL certificate paths in Nginx config
sed -i "s|ssl_certificate /etc/nginx/ssl/rpc.crt;|ssl_certificate $CERT_PATH;|" /etc/nginx/sites-available/rpc-core
sed -i "s|ssl_certificate_key /etc/nginx/ssl/rpc.key;|ssl_certificate_key $KEY_PATH;|" /etc/nginx/sites-available/rpc-core

# Add domain to server_name if not present
if ! grep -q "$DOMAIN" /etc/nginx/sites-available/rpc-core; then
    sed -i "s|server_name.*rpc-core.besu.local|server_name $DOMAIN rpc-core.besu.local|" /etc/nginx/sites-available/rpc-core
fi

# Test configuration
nginx -t
UPDATE_NGINX

if [ $? -eq 0 ]; then
    log_success "Nginx configuration updated"
else
    log_error "Failed to update Nginx configuration"
    exit 1
fi

# Reload Nginx
log_info ""
log_info "5. Reloading Nginx..."
sshpass -p 'L@kers2010' ssh -o StrictHostKeyChecking=no root@${PROXMOX_HOST} \
    "pct exec $VMID -- systemctl reload nginx"

log_success "Nginx reloaded"

# Set up auto-renewal
log_info ""
log_info "6. Setting up auto-renewal..."
sshpass -p 'L@kers2010' ssh -o StrictHostKeyChecking=no root@${PROXMOX_HOST} \
    "pct exec $VMID -- systemctl enable certbot.timer && systemctl start certbot.timer"

log_success "Auto-renewal enabled"

# Verify certificate
log_info ""
log_info "7. Verifying certificate..."
CERT_INFO=$(sshpass -p 'L@kers2010' ssh -o StrictHostKeyChecking=no root@${PROXMOX_HOST} \
    "pct exec $VMID -- openssl x509 -in $CERT_PATH -noout -subject -issuer -dates 2>&1")

log_info "Certificate details:"
echo "$CERT_INFO" | while read line; do
    log_info "  $line"
done

# Test HTTPS
log_info ""
log_info "8. Testing HTTPS endpoint..."
HTTPS_TEST=$(sshpass -p 'L@kers2010' ssh -o StrictHostKeyChecking=no root@${PROXMOX_HOST} \
    "pct exec $VMID -- timeout 5 curl -s -X POST https://localhost:443 \
    -H 'Content-Type: application/json' \
    -d '{\"jsonrpc\":\"2.0\",\"method\":\"eth_blockNumber\",\"params\":[],\"id\":1}' 2>&1" || echo "FAILED")

if echo "$HTTPS_TEST" | grep -q "result"; then
    log_success "HTTPS endpoint is working!"
else
    log_warn "HTTPS test inconclusive"
fi

echo ""
log_success "Let's Encrypt certificate setup complete!"
echo ""
log_info "Summary:"
log_info "  ✓ Certificate obtained for: $DOMAIN"
log_info "  ✓ Nginx configuration updated"
log_info "  ✓ Auto-renewal enabled"
echo ""
if echo "$CERTBOT_OUTPUT" | grep -q "staging"; then
    log_warn "NOTE: Certificate is from STAGING server (for testing)"
    log_info "To get production certificate, run:"
    log_info "  pct exec $VMID -- certbot certonly --dns-cloudflare \\"
    log_info "    --dns-cloudflare-credentials /etc/cloudflare/credentials.ini \\"
    log_info "    --non-interactive --agree-tos \\"
    log_info "    --email admin@$(echo $DOMAIN | cut -d. -f2-) -d $DOMAIN"
fi

