#!/usr/bin/env bash
# Set up Let's Encrypt certificate for RPC-01 (VMID 2500)
# Usage: ./setup-letsencrypt-rpc-2500.sh [domain1] [domain2] ...
# If no domains provided, will use configured server_name from Nginx config

set -e

VMID=2500
PROXMOX_HOST="192.168.11.10"

# 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 for RPC-01 (VMID $VMID)"
echo ""

# Get domains from arguments or from Nginx config
if [ $# -gt 0 ]; then
    DOMAINS=("$@")
    log_info "Using provided domains: ${DOMAINS[*]}"
else
    log_info "Extracting domains from Nginx configuration..."
    DOMAINS=$(sshpass -p 'L@kers2010' ssh -o StrictHostKeyChecking=no root@${PROXMOX_HOST} \
        "pct exec $VMID -- grep -E 'server_name' /etc/nginx/sites-available/rpc-core | \
        grep -v '^#' | sed 's/.*server_name //;s/;.*//' | tr ' ' '\n' | \
        grep -v '^$' | grep -v '^besu-rpc-1$' | grep -v '^192\.168\.' | head -5" 2>&1)
    
    if [ -z "$DOMAINS" ]; then
        log_warn "No domains found in Nginx config"
        log_info "Please provide domains as arguments:"
        log_info "  ./setup-letsencrypt-rpc-2500.sh rpc-core.besu.local rpc-core.chainid138.local"
        exit 1
    fi
    
    DOMAINS_ARRAY=($DOMAINS)
    log_info "Found domains: ${DOMAINS_ARRAY[*]}"
fi

# Check if certbot is installed
log_info ""
log_info "1. Checking Certbot installation..."
if ! sshpass -p 'L@kers2010' ssh -o StrictHostKeyChecking=no root@${PROXMOX_HOST} \
    "pct exec $VMID -- which certbot >/dev/null 2>&1"; then
    log_info "Installing Certbot..."
    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 python3-certbot-nginx
        '" || {
        log_error "Failed to install Certbot"
        exit 1
    }
    log_success "Certbot installed"
else
    log_success "Certbot already installed"
fi

# Check if domains are accessible
log_info ""
log_info "2. Verifying domain accessibility..."
for domain in "${DOMAINS_ARRAY[@]}"; do
    log_info "Checking domain: $domain"
    
    # Check if domain resolves
    RESOLVED_IP=$(sshpass -p 'L@kers2010' ssh -o StrictHostKeyChecking=no root@${PROXMOX_HOST} \
        "pct exec $VMID -- getent hosts $domain 2>&1 | awk '{print \$1}' | head -1" || echo "")
    
    if [ -z "$RESOLVED_IP" ]; then
        log_warn "Domain $domain does not resolve. DNS may need to be configured."
        log_info "Let's Encrypt will use HTTP-01 challenge (requires port 80 accessible)"
    else
        log_info "Domain $domain resolves to: $RESOLVED_IP"
    fi
done

# Check if port 80 is accessible (required for HTTP-01 challenge)
log_info ""
log_info "3. Checking port 80 accessibility..."
if sshpass -p 'L@kers2010' ssh -o StrictHostKeyChecking=no root@${PROXMOX_HOST} \
    "pct exec $VMID -- ss -tln | grep -q ':80 '"; then
    log_success "Port 80 is listening (required for HTTP-01 challenge)"
else
    log_error "Port 80 is not listening. Let's Encrypt HTTP-01 challenge requires port 80."
    log_info "Options:"
    log_info "  1. Ensure port 80 is accessible from internet"
    log_info "  2. Use DNS-01 challenge instead (requires DNS API access)"
    exit 1
fi

# Obtain certificate
log_info ""
log_info "4. Obtaining Let's Encrypt certificate..."
log_info "Domains: ${DOMAINS_ARRAY[*]}"
log_warn "This will use Let's Encrypt staging server for testing first"
log_info "Press Ctrl+C to cancel, or wait 5 seconds to continue..."
sleep 5

# Use staging first for testing
STAGING_FLAG="--staging"
log_info "Using Let's Encrypt staging server (for testing)"

# Build certbot command
CERTBOT_CMD="certbot --nginx $STAGING_FLAG --non-interactive --agree-tos --email admin@$(echo ${DOMAINS_ARRAY[0]} | cut -d. -f2-)"
for domain in "${DOMAINS_ARRAY[@]}"; do
    CERTBOT_CMD="$CERTBOT_CMD -d $domain"
done

log_info "Running: $CERTBOT_CMD"

# Run certbot
CERTBOT_OUTPUT=$(sshpass -p 'L@kers2010' ssh -o StrictHostKeyChecking=no root@${PROXMOX_HOST} \
    "pct exec $VMID -- bash -c '$CERTBOT_CMD' 2>&1" || echo "FAILED")

if echo "$CERTBOT_OUTPUT" | grep -q "Congratulations\|Successfully"; then
    log_success "Certificate obtained successfully!"
    
    # If using staging, offer to get production certificate
    if echo "$CERTBOT_CMD" | grep -q "staging"; then
        log_info ""
        log_warn "Certificate obtained from STAGING server (for testing)"
        log_info "To get production certificate, run:"
        log_info "  pct exec $VMID -- certbot --nginx --non-interactive --agree-tos --email admin@$(echo ${DOMAINS_ARRAY[0]} | cut -d. -f2-) -d ${DOMAINS_ARRAY[*]}"
    fi
else
    log_error "Certificate acquisition failed"
    log_info "Output: $CERTBOT_OUTPUT"
    log_info ""
    log_info "Common issues:"
    log_info "  1. Domain not accessible from internet (DNS not configured)"
    log_info "  2. Port 80 not accessible from internet (firewall/NAT issue)"
    log_info "  3. Domain already has certificate (use --force-renewal)"
    log_info ""
    log_info "For DNS-01 challenge (if HTTP-01 fails):"
    log_info "  pct exec $VMID -- certbot certonly --manual --preferred-challenges dns -d ${DOMAINS_ARRAY[0]}"
    exit 1
fi

# Verify certificate
log_info ""
log_info "5. Verifying certificate..."
CERT_PATH=$(sshpass -p 'L@kers2010' ssh -o StrictHostKeyChecking=no root@${PROXMOX_HOST} \
    "pct exec $VMID -- certbot certificates 2>&1 | grep -A1 '${DOMAINS_ARRAY[0]}' | grep 'Certificate Path' | awk '{print \$3}'" || echo "")

if [ -n "$CERT_PATH" ]; then
    log_success "Certificate found at: $CERT_PATH"
    
    # Check certificate details
    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
else
    log_warn "Could not verify certificate path"
fi

# Test Nginx configuration
log_info ""
log_info "6. Testing Nginx configuration..."
if sshpass -p 'L@kers2010' ssh -o StrictHostKeyChecking=no root@${PROXMOX_HOST} \
    "pct exec $VMID -- nginx -t 2>&1 | grep -q 'successful'"; then
    log_success "Nginx configuration is valid"
    
    # Reload Nginx
    sshpass -p 'L@kers2010' ssh -o StrictHostKeyChecking=no root@${PROXMOX_HOST} \
        "pct exec $VMID -- systemctl reload nginx"
    log_success "Nginx reloaded"
else
    log_error "Nginx configuration test failed"
    exit 1
fi

# Test HTTPS endpoint
log_info ""
log_info "7. 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 (may need external access)"
fi

# Set up auto-renewal
log_info ""
log_info "8. Setting up auto-renewal..."
if sshpass -p 'L@kers2010' ssh -o StrictHostKeyChecking=no root@${PROXMOX_HOST} \
    "pct exec $VMID -- systemctl is-enabled certbot.timer >/dev/null 2>&1"; then
    log_success "Certbot timer already enabled"
else
    sshpass -p 'L@kers2010' ssh -o StrictHostKeyChecking=no root@${PROXMOX_HOST} \
        "pct exec $VMID -- systemctl enable certbot.timer && systemctl start certbot.timer"
    log_success "Certbot timer enabled"
fi

# Test renewal
log_info ""
log_info "9. Testing certificate renewal..."
RENEWAL_TEST=$(sshpass -p 'L@kers2010' ssh -o StrictHostKeyChecking=no root@${PROXMOX_HOST} \
    "pct exec $VMID -- certbot renew --dry-run 2>&1 | tail -5")

if echo "$RENEWAL_TEST" | grep -q "The dry run was successful\|Congratulations"; then
    log_success "Certificate renewal test passed"
else
    log_warn "Renewal test had issues (may be normal for staging cert)"
    log_info "Output: $RENEWAL_TEST"
fi

echo ""
log_success "Let's Encrypt certificate setup complete!"
echo ""
log_info "Summary:"
log_info "  ✓ Certbot installed"
log_info "  ✓ Certificate obtained for: ${DOMAINS_ARRAY[*]}"
log_info "  ✓ Nginx configuration updated"
log_info "  ✓ Auto-renewal enabled"
echo ""
log_info "Certificate location:"
log_info "  $(sshpass -p 'L@kers2010' ssh -o StrictHostKeyChecking=no root@${PROXMOX_HOST} "pct exec $VMID -- certbot certificates 2>&1 | grep -A2 '${DOMAINS_ARRAY[0]}' | head -5")"
echo ""
if echo "$CERTBOT_CMD" | 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 --nginx --non-interactive --agree-tos --email admin@$(echo ${DOMAINS_ARRAY[0]} | cut -d. -f2-) -d ${DOMAINS_ARRAY[*]}"
fi

