#!/bin/bash
# Configure HAProxy Load Balancers for AiWorker K3s Cluster

set -e

GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'

echo -e "${GREEN}🔧 Configuring Load Balancers${NC}"

LB_IPS=("108.165.47.221" "108.165.47.203")
LB_NAMES=("k8s-lb-01" "k8s-lb-02")

# Get Nginx Ingress NodePort ports
echo -e "\n${YELLOW}Getting Nginx Ingress NodePorts...${NC}"
HTTP_PORT=$(kubectl --kubeconfig ~/.kube/aiworker-config get svc -n ingress-nginx ingress-nginx-controller -o jsonpath='{.spec.ports[?(@.port==80)].nodePort}')
HTTPS_PORT=$(kubectl --kubeconfig ~/.kube/aiworker-config get svc -n ingress-nginx ingress-nginx-controller -o jsonpath='{.spec.ports[?(@.port==443)].nodePort}')

echo "  HTTP NodePort: ${HTTP_PORT}"
echo "  HTTPS NodePort: ${HTTPS_PORT}"

# Create HAProxy configuration
cat > /tmp/haproxy.cfg <<EOF
global
    log /dev/log local0
    log /dev/log local1 notice
    chroot /var/lib/haproxy
    stats socket /run/haproxy/admin.sock mode 660 level admin
    stats timeout 30s
    user haproxy
    group haproxy
    daemon
    maxconn 4000

defaults
    log     global
    mode    http
    option  httplog
    option  dontlognull
    timeout connect 5000
    timeout client  50000
    timeout server  50000

# Frontend HTTP (port 80)
frontend http_frontend
    bind *:80
    mode http
    option httplog
    option forwardfor
    default_backend http_backend

# Backend HTTP - Workers NodePort ${HTTP_PORT}
backend http_backend
    mode http
    balance roundrobin
    option httpchk GET /healthz
    http-check expect status 200
    server k8s-worker-01 10.100.0.5:${HTTP_PORT} check
    server k8s-worker-02 10.100.0.6:${HTTP_PORT} check
    server k8s-worker-03 10.100.0.7:${HTTP_PORT} check

# Frontend HTTPS (port 443)
frontend https_frontend
    bind *:443
    mode tcp
    option tcplog
    default_backend https_backend

# Backend HTTPS - Workers NodePort ${HTTPS_PORT} (TCP passthrough)
backend https_backend
    mode tcp
    balance roundrobin
    option tcp-check
    server k8s-worker-01 10.100.0.5:${HTTPS_PORT} check
    server k8s-worker-02 10.100.0.6:${HTTPS_PORT} check
    server k8s-worker-03 10.100.0.7:${HTTPS_PORT} check

# Stats interface
frontend stats
    bind *:8404
    mode http
    stats enable
    stats uri /stats
    stats refresh 10s
    stats auth admin:aiworker2026
EOF

# Deploy to both load balancers
for i in 0 1; do
  echo -e "\n${YELLOW}Configuring ${LB_NAMES[$i]}...${NC}"

  # Install HAProxy if not installed
  ssh root@${LB_IPS[$i]} "which haproxy || (apt update && apt install -y haproxy)"

  # Deploy configuration
  scp /tmp/haproxy.cfg root@${LB_IPS[$i]}:/etc/haproxy/haproxy.cfg

  # Restart HAProxy
  ssh root@${LB_IPS[$i]} "systemctl restart haproxy && systemctl enable haproxy"

  # Verify
  if ssh root@${LB_IPS[$i]} "systemctl is-active haproxy" | grep -q "active"; then
    echo -e "${GREEN}✓ ${LB_NAMES[$i]} configured and running${NC}"
  else
    echo -e "${RED}✗ ${LB_NAMES[$i]} failed to start${NC}"
    exit 1
  fi
done

echo -e "\n${GREEN}========================================${NC}"
echo -e "${GREEN}✅ Load Balancers configured!${NC}"
echo -e "${GREEN}========================================${NC}"
echo ""
echo -e "📊 HAProxy Stats:"
echo -e "  LB-01: http://108.165.47.221:8404/stats"
echo -e "  LB-02: http://108.165.47.203:8404/stats"
echo -e "  Credentials: admin / aiworker2026"
echo ""
echo -e "🌐 DNS Configuration:"
echo -e "  *.fuq.tv    A  108.165.47.221"
echo -e "  *.fuq.tv    A  108.165.47.203"
echo -e "  *.r.fuq.tv  A  108.165.47.221"
echo -e "  *.r.fuq.tv  A  108.165.47.203"
echo ""
echo -e "🧪 Test access:"
echo -e "  curl https://test.fuq.tv"

rm /tmp/haproxy.cfg
