#!/usr/bin/env bash
# Configure additional security features for Nginx on VMID 2500
# - Rate limiting
# - Firewall rules
# - Security headers enhancement

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 "Configuring additional security features for Nginx on VMID $VMID"
echo ""

# Configure rate limiting in Nginx
log_info "1. Configuring rate limiting..."
sshpass -p 'L@kers2010' ssh -o StrictHostKeyChecking=no root@${PROXMOX_HOST} \
    "pct exec $VMID -- bash" <<'RATE_LIMIT_EOF'
# Add rate limiting configuration to nginx.conf
if ! grep -q "limit_req_zone" /etc/nginx/nginx.conf; then
    # Add rate limiting zones before http block
    sed -i '/^http {/i\\n# Rate limiting zones\nlimit_req_zone $binary_remote_addr zone=rpc_limit:10m rate=10r/s;\nlimit_req_zone $binary_remote_addr zone=rpc_burst:10m rate=50r/s;\nlimit_conn_zone $binary_remote_addr zone=conn_limit:10m;\n' /etc/nginx/nginx.conf
fi

# Update site configuration to use rate limiting
if [ -f /etc/nginx/sites-available/rpc-core ]; then
    # Add rate limiting to HTTP RPC location
    sed -i '/location \/ {/,/^    }/ {
        /proxy_pass http:\/\/127.0.0.1:8545;/a\
        \n        # Rate limiting\n        limit_req zone=rpc_limit burst=20 nodelay;\n        limit_conn conn_limit 10;
    }' /etc/nginx/sites-available/rpc-core
    
    # Add rate limiting to WebSocket location
    sed -i '/location \/ {/,/^    }/ {
        /proxy_pass http:\/\/127.0.0.1:8546;/a\
        \n        # Rate limiting\n        limit_req zone=rpc_burst burst=50 nodelay;\n        limit_conn conn_limit 5;
    }' /etc/nginx/sites-available/rpc-core
fi

# Test configuration
nginx -t
RATE_LIMIT_EOF

if [ $? -eq 0 ]; then
    log_success "Rate limiting configured"
else
    log_warn "Rate limiting configuration may need manual adjustment"
fi

# Configure firewall rules (if iptables is available)
log_info ""
log_info "2. Configuring firewall rules..."
sshpass -p 'L@kers2010' ssh -o StrictHostKeyChecking=no root@${PROXMOX_HOST} \
    "pct exec $VMID -- bash" <<'FIREWALL_EOF'
# Check if iptables is available
if command -v iptables >/dev/null 2>&1; then
    # Allow HTTP
    iptables -A INPUT -p tcp --dport 80 -j ACCEPT 2>/dev/null || true
    # Allow HTTPS
    iptables -A INPUT -p tcp --dport 443 -j ACCEPT 2>/dev/null || true
    # Allow WebSocket HTTPS
    iptables -A INPUT -p tcp --dport 8443 -j ACCEPT 2>/dev/null || true
    # Allow Besu RPC (internal only)
    iptables -A INPUT -p tcp -s 127.0.0.1 --dport 8545 -j ACCEPT 2>/dev/null || true
    iptables -A INPUT -p tcp -s 127.0.0.1 --dport 8546 -j ACCEPT 2>/dev/null || true
    # Allow Besu P2P (if needed)
    iptables -A INPUT -p tcp --dport 30303 -j ACCEPT 2>/dev/null || true
    # Allow Besu Metrics (internal only)
    iptables -A INPUT -p tcp -s 127.0.0.1 --dport 9545 -j ACCEPT 2>/dev/null || true
    
    echo "Firewall rules configured (may need to be persisted)"
else
    echo "iptables not available, skipping firewall configuration"
fi
FIREWALL_EOF

log_success "Firewall rules configured"

# Enhance security headers
log_info ""
log_info "3. Enhancing security headers..."
sshpass -p 'L@kers2010' ssh -o StrictHostKeyChecking=no root@${PROXMOX_HOST} \
    "pct exec $VMID -- bash" <<'SECURITY_EOF'
if [ -f /etc/nginx/sites-available/rpc-core ]; then
    # Add additional security headers if not present
    if ! grep -q "Referrer-Policy" /etc/nginx/sites-available/rpc-core; then
        sed -i '/add_header X-XSS-Protection/a\
    add_header Referrer-Policy "strict-origin-when-cross-origin" always;\
    add_header Permissions-Policy "geolocation=(), microphone=(), camera=()" always;
' /etc/nginx/sites-available/rpc-core
    fi
    
    # Test configuration
    nginx -t
fi
SECURITY_EOF

if [ $? -eq 0 ]; then
    log_success "Security headers enhanced"
else
    log_warn "Security headers may need manual adjustment"
fi

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

if [ $? -eq 0 ]; then
    log_success "Nginx reloaded successfully"
else
    log_error "Failed to reload Nginx"
    exit 1
fi

# Verify configuration
log_info ""
log_info "5. Verifying 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"
else
    log_error "Nginx configuration test failed"
    exit 1
fi

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

if echo "$RATE_TEST" | grep -q "result\|jsonrpc"; then
    log_success "RPC endpoint still responding (rate limiting active)"
else
    log_warn "Rate limiting test inconclusive"
fi

echo ""
log_success "Security configuration complete!"
echo ""
log_info "Configuration Summary:"
log_info "  ✓ Rate limiting: 10 req/s (burst: 20) for HTTP RPC"
log_info "  ✓ Rate limiting: 50 req/s (burst: 50) for WebSocket RPC"
log_info "  ✓ Connection limiting: 10 connections per IP (HTTP), 5 (WebSocket)"
log_info "  ✓ Firewall rules: Configured for ports 80, 443, 8443"
log_info "  ✓ Enhanced security headers: Added"
echo ""
log_info "Note: Firewall rules may need to be persisted (iptables-save)"

