#!/usr/bin/env bash
# Complete Let's Encrypt setup with automated DNS record creation
# Usage: ./setup-letsencrypt-with-dns.sh [API_TOKEN]

set -e

VMID=2500
DOMAIN="rpc-core.d-bis.org"
NAME="rpc-core"
IP="192.168.11.250"
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 "Complete Let's Encrypt Setup with Automated DNS"
log_info "Domain: $DOMAIN"
echo ""

# Get API token
if [ -n "$1" ]; then
    API_TOKEN="$1"
    log_info "Using provided API token"
elif [ -f .env ]; then
    source .env 2>/dev/null
    if [ -n "$CLOUDFLARE_API_TOKEN" ]; then
        API_TOKEN="$CLOUDFLARE_API_TOKEN"
        log_info "Using API token from .env file"
    else
        log_error "CLOUDFLARE_API_TOKEN not found in .env file"
        log_info "Please provide API token: $0 <API_TOKEN>"
        exit 1
    fi
else
    log_error "No API token provided and no .env file found"
    log_info "Usage: $0 [API_TOKEN]"
    log_info ""
    log_info "To get API token:"
    log_info "  1. Go to https://dash.cloudflare.com/profile/api-tokens"
    log_info "  2. Create Token with: Zone → DNS:Edit → d-bis.org"
    exit 1
fi

# Step 1: Create DNS record
log_info ""
log_info "Step 1: Creating DNS record..."
if [ -f scripts/create-dns-record-rpc-core.sh ]; then
    ./scripts/create-dns-record-rpc-core.sh "$API_TOKEN" 2>&1
    DNS_RESULT=$?
else
    log_error "create-dns-record-rpc-core.sh not found"
    exit 1
fi

if [ $DNS_RESULT -ne 0 ]; then
    log_error "Failed to create DNS record"
    exit 1
fi

log_success "DNS record created"

# Step 2: Wait for DNS propagation
log_info ""
log_info "Step 2: Waiting for DNS propagation (30 seconds)..."
sleep 30

# Step 3: Verify DNS resolution
log_info ""
log_info "Step 3: Verifying DNS resolution..."
DNS_CHECK=$(sshpass -p 'L@kers2010' ssh -o StrictHostKeyChecking=no root@${PROXMOX_HOST} \
    "pct exec $VMID -- getent hosts $DOMAIN 2>&1" || echo "NOT_RESOLVED")

if echo "$DNS_CHECK" | grep -q "NOT_RESOLVED\|not found"; then
    log_warn "DNS not yet resolved. Waiting another 30 seconds..."
    sleep 30
    DNS_CHECK=$(sshpass -p 'L@kers2010' ssh -o StrictHostKeyChecking=no root@${PROXMOX_HOST} \
        "pct exec $VMID -- getent hosts $DOMAIN 2>&1" || echo "NOT_RESOLVED")
fi

if echo "$DNS_CHECK" | grep -q "$IP\|NOT_RESOLVED"; then
    log_info "DNS check: $DNS_CHECK"
    log_warn "DNS may still be propagating. Continuing anyway..."
else
    log_success "DNS resolved"
fi

# Step 4: Obtain Let's Encrypt certificate
log_info ""
log_info "Step 4: Obtaining Let's Encrypt certificate..."
CERTBOT_OUTPUT=$(sshpass -p 'L@kers2010' ssh -o StrictHostKeyChecking=no root@${PROXMOX_HOST} \
    "pct exec $VMID -- certbot --nginx \
        --non-interactive \
        --agree-tos \
        --email admin@d-bis.org \
        -d $DOMAIN \
        --redirect 2>&1" || echo "FAILED")

if echo "$CERTBOT_OUTPUT" | grep -q "Successfully received certificate\|Congratulations"; then
    log_success "Certificate obtained successfully!"
elif echo "$CERTBOT_OUTPUT" | grep -q "NXDOMAIN\|DNS problem"; then
    log_warn "DNS may still be propagating. Waiting 60 more seconds..."
    sleep 60
    log_info "Retrying certificate acquisition..."
    CERTBOT_OUTPUT=$(sshpass -p 'L@kers2010' ssh -o StrictHostKeyChecking=no root@${PROXMOX_HOST} \
        "pct exec $VMID -- certbot --nginx \
            --non-interactive \
            --agree-tos \
            --email admin@d-bis.org \
            -d $DOMAIN \
            --redirect 2>&1" || echo "FAILED")
    
    if echo "$CERTBOT_OUTPUT" | grep -q "Successfully received certificate\|Congratulations"; then
        log_success "Certificate obtained successfully!"
    else
        log_error "Certificate acquisition failed"
        log_info "Output: $CERTBOT_OUTPUT"
        log_info ""
        log_info "Possible issues:"
        log_info "  1. DNS still propagating (wait 5-10 minutes and retry)"
        log_info "  2. Port 80 not accessible from internet"
        log_info "  3. Firewall blocking Let's Encrypt validation"
        exit 1
    fi
else
    log_error "Certificate acquisition failed"
    log_info "Output: $CERTBOT_OUTPUT"
    exit 1
fi

# Step 5: Verify certificate
log_info ""
log_info "Step 5: Verifying certificate..."
CERT_INFO=$(sshpass -p 'L@kers2010' ssh -o StrictHostKeyChecking=no root@${PROXMOX_HOST} \
    "pct exec $VMID -- certbot certificates 2>&1 | grep -A5 '$DOMAIN'" || echo "")

if [ -n "$CERT_INFO" ]; then
    log_success "Certificate verified"
    echo "$CERT_INFO" | while read line; do
        log_info "  $line"
    done
else
    log_warn "Could not verify certificate details"
fi

# Step 6: Test HTTPS
log_info ""
log_info "Step 6: 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!"
    log_info "Response: $HTTPS_TEST"
else
    log_warn "HTTPS test inconclusive"
fi

# Step 7: Verify auto-renewal
log_info ""
log_info "Step 7: Verifying 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 "Auto-renewal is enabled"
else
    log_warn "Auto-renewal may not be enabled"
fi

echo ""
log_success "Let's Encrypt setup complete!"
echo ""
log_info "Summary:"
log_info "  ✓ DNS record created: $DOMAIN → $IP"
log_info "  ✓ Certificate obtained: $DOMAIN"
log_info "  ✓ Nginx configured with Let's Encrypt certificate"
log_info "  ✓ Auto-renewal enabled"
echo ""
log_info "Certificate location:"
log_info "  /etc/letsencrypt/live/$DOMAIN/"
echo ""
log_info "Test HTTPS:"
log_info "  curl -X POST https://$DOMAIN -H 'Content-Type: application/json' -d '{\"jsonrpc\":\"2.0\",\"method\":\"eth_blockNumber\",\"params\":[],\"id\":1}'"

