#!/bin/bash

# A script to create an EKS cluster with a managed node group using eksctl.
# This script assumes eksctl and kubectl are already installed and configured.

# --- Configuration ---
REGION="us-east-1"
CLUSTER_NAME="my-cli-eks-cluster"
NODE_GROUP_NAME="standard-workers"
NODE_TYPE="t3.medium"
NODES_COUNT=2
KUBERNETES_VERSION="1.28" # Specify a supported Kubernetes version

# --- 1. Create EKS Cluster ---
echo "--- Creating EKS Cluster: $CLUSTER_NAME with a managed node group ---"
echo "This may take 15-20 minutes."

eksctl create cluster \
  --name $CLUSTER_NAME \
  --region $REGION \
  --version $KUBERNETES_VERSION \
  --nodegroup-name $NODE_GROUP_NAME \
  --node-type $NODE_TYPE \
  --nodes $NODES_COUNT \
  --nodes-min 1 \
  --nodes-max 3 \
  --managed \
  --with-oidc # Enable OIDC provider for IRSA (IAM Roles for Service Accounts)

if [ $? -ne 0 ]; then
  echo "Error creating EKS cluster. Exiting."
  exit 1
fi

echo "EKS Cluster '$CLUSTER_NAME' created successfully."

# --- 2. Update Kubeconfig ---
echo -e "\n--- Updating kubeconfig to access the new cluster ---"
aws eks update-kubeconfig \
  --name $CLUSTER_NAME \
  --region $REGION

echo "Kubeconfig updated. You can now use 'kubectl' to interact with the cluster."
echo "Example: kubectl get nodes"

read -p "Press Enter to delete the EKS cluster and clean up resources..."

# --- Clean Up ---
echo -e "\n--- Deleting EKS Cluster: $CLUSTER_NAME ---"
echo "This may take 10-15 minutes."

eksctl delete cluster \
  --name $CLUSTER_NAME \
  --region $REGION

if [ $? -ne 0 ]; then
  echo "Error deleting EKS cluster. Manual cleanup may be required."
  exit 1
fi

echo "EKS Cluster '$CLUSTER_NAME' deleted successfully."

echo -e "\n--- EKS cluster demonstration and cleanup complete ---"
