#!/bin/bash
# ----------------------------------------------------
# Cirries Diverter EKS Setup Script (Cluster + Namespace only)
# ----------------------------------------------------

set -e

COLLECTOR_IP="$1"
REGION="us-east-1"
CLUSTER_NAME="cirries-diverter-eks"
NAMESPACE="cirries"
NODEGROUP_NAME="ubuntu-nodes"
EKS_NODE_TYPE="t3.medium"
K8S_VERSION="1.32"

if [ -z "$COLLECTOR_IP" ]; then
  echo "❌ Usage: $0 <Collector_IP>"
  exit 1
fi

echo "🚀 Starting EKS setup for Cirries Diverter"
echo "Region: $REGION"
echo "Cluster: $CLUSTER_NAME"
echo "Collector IP: $COLLECTOR_IP"
echo "----------------------------------------"

# ---- Create EKS Cluster with Ubuntu nodes ----
if ! eksctl get cluster --region $REGION | grep -q "$CLUSTER_NAME"; then
  echo "☸️ Creating EKS Cluster ($CLUSTER_NAME)... this may take 10–15 mins"
  eksctl create cluster \
    --name $CLUSTER_NAME \
    --region $REGION \
    --version $K8S_VERSION \
    --nodegroup-name $NODEGROUP_NAME \
    --node-type $EKS_NODE_TYPE \
    --nodes 2 \
    --nodes-min 2 \
    --nodes-max 3 \
    --with-oidc \
    --ssh-access \
    --ssh-public-key "PMCPerformance" \
    --managed \
    --node-ami-family Ubuntu2204
else
  echo "✅ Cluster already exists: $CLUSTER_NAME"
fi

# ---- Configure kubectl ----
echo "🔧 Configuring kubectl..."
aws eks update-kubeconfig --region $REGION --name $CLUSTER_NAME

# ---- Verify nodes ----
echo "🔍 Checking cluster nodes..."
kubectl get nodes -o wide

# ---- Namespace ----
echo "📦 Creating namespace if not present..."
kubectl create namespace $NAMESPACE || true

echo ""
echo "✅ EKS Cluster '$CLUSTER_NAME' and namespace '$NAMESPACE' are ready."
echo "----------------------------------------"
echo "Next steps:"
echo "1️⃣  Edit your DaemonSet YAML (AWSEKS1Gbps.yaml) and replace <Collector_IP> with $COLLECTOR_IP"
echo "2️⃣  Deploy the DaemonSet manually using:"
echo "    kubectl apply -f AWSEKS1Gbps.yaml -n $NAMESPACE"
echo ""
echo "3️⃣  Verify DaemonSet and pods:"
echo "    kubectl get ds,pods -n $NAMESPACE -o wide"
echo ""
echo "4️⃣  View logs:"
echo "    kubectl logs -n $NAMESPACE -l app=cirries-diverter -f"
echo ""
