#!/bin/bash
#
# Citadel Cilium Installation Script
# Installs Cilium CNI with Hubble observability and full security features
#

set -e

echo "=========================================="
echo "  Citadel Cilium Installation"
echo "  eBPF-Based Networking & Security"
echo "=========================================="
echo ""

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# Set kubeconfig
export KUBECONFIG=/etc/rancher/k3s/k3s.yaml

# Check if kubectl works
if ! kubectl get nodes &>/dev/null; then
    echo -e "${RED}Error: Cannot connect to Kubernetes cluster${NC}"
    echo "Make sure K3s is running and KUBECONFIG is set"
    exit 1
fi

echo -e "${GREEN}Connected to K3s cluster${NC}"
echo ""

# Step 1: Install Helm if not present
echo -e "${YELLOW}Step 1: Installing Helm...${NC}"
if ! command -v helm &>/dev/null; then
    curl https://raw.githubusercontent.com/helm/helm/main/scripts/get-helm-3 | bash
    echo -e "${GREEN}Helm installed${NC}"
else
    echo -e "${GREEN}Helm already installed: $(helm version --short)${NC}"
fi
echo ""

# Step 2: Add Cilium Helm repository
echo -e "${YELLOW}Step 2: Adding Cilium Helm repository...${NC}"
helm repo add cilium https://helm.cilium.io 2>/dev/null || true
helm repo update
echo -e "${GREEN}Cilium repo added${NC}"
echo ""

# Step 3: Install Cilium with full features
echo -e "${YELLOW}Step 3: Installing Cilium with Citadel configuration...${NC}"
echo ""
echo "Features being installed:"
echo "  - eBPF-based CNI networking"
echo "  - kube-proxy replacement (eBPF load balancing)"
echo "  - Hubble network observability"
echo "  - Hubble Relay (cluster-wide visibility)"
echo "  - Hubble UI (visual network maps)"
echo "  - Prometheus metrics integration"
echo "  - Mutual authentication via SPIRE (mTLS)"
echo ""

CILIUM_VERSION="1.18.6"

helm upgrade --install cilium cilium/cilium \
  --version "$CILIUM_VERSION" \
  --namespace kube-system \
  --set ipam.operator.clusterPoolIPv4PodCIDRList="10.42.0.0/16" \
  --set kubeProxyReplacement=true \
  --set k8sServiceHost="127.0.0.1" \
  --set k8sServicePort="6443" \
  --set hubble.enabled=true \
  --set hubble.relay.enabled=true \
  --set hubble.ui.enabled=true \
  --set hubble.metrics.enabled=true \
  --set prometheus.enabled=true \
  --set operator.prometheus.enabled=true \
  --set bpf.lbMapMax=131072 \
  --set authentication.mutual.spire.enabled=true \
  --set authentication.mutual.spire.install.enabled=true \
  --set authentication.mutual.spire.install.server.dataStore=sqlite3 \
  --set authentication.mutual.spire.install.agent.socketPath=/run/spire/agent/agent.sock \
  --wait

echo ""
echo -e "${GREEN}Cilium installed${NC}"
echo ""

# Step 4: Install Cilium CLI
echo -e "${YELLOW}Step 4: Installing Cilium CLI...${NC}"
if ! command -v cilium &>/dev/null; then
    CILIUM_CLI_VERSION=$(curl -s https://raw.githubusercontent.com/cilium/cilium-cli/main/stable.txt)
    CLI_ARCH=$(uname -m)
    if [ "$CLI_ARCH" = "x86_64" ]; then CLI_ARCH="amd64"; fi
    if [ "$CLI_ARCH" = "aarch64" ]; then CLI_ARCH="arm64"; fi

    curl -L --fail --remote-name-all \
        "https://github.com/cilium/cilium-cli/releases/download/${CILIUM_CLI_VERSION}/cilium-linux-${CLI_ARCH}.tar.gz" \
        "https://github.com/cilium/cilium-cli/releases/download/${CILIUM_CLI_VERSION}/cilium-linux-${CLI_ARCH}.tar.gz.sha256sum"

    sha256sum --check "cilium-linux-${CLI_ARCH}.tar.gz.sha256sum"
    tar xzvfC "cilium-linux-${CLI_ARCH}.tar.gz" /usr/local/bin
    rm -f cilium-linux-${CLI_ARCH}.tar.gz*
    echo -e "${GREEN}Cilium CLI installed${NC}"
else
    echo -e "${GREEN}Cilium CLI already installed: $(cilium version --client)${NC}"
fi
echo ""

# Step 5: Install Hubble CLI
echo -e "${YELLOW}Step 5: Installing Hubble CLI...${NC}"
if ! command -v hubble &>/dev/null; then
    HUBBLE_VERSION=$(curl -s https://raw.githubusercontent.com/cilium/hubble/master/stable.txt)
    HUBBLE_ARCH=$(uname -m)
    if [ "$HUBBLE_ARCH" = "x86_64" ]; then HUBBLE_ARCH="amd64"; fi
    if [ "$HUBBLE_ARCH" = "aarch64" ]; then HUBBLE_ARCH="arm64"; fi

    curl -L --fail --remote-name-all \
        "https://github.com/cilium/hubble/releases/download/${HUBBLE_VERSION}/hubble-linux-${HUBBLE_ARCH}.tar.gz" \
        "https://github.com/cilium/hubble/releases/download/${HUBBLE_VERSION}/hubble-linux-${HUBBLE_ARCH}.tar.gz.sha256sum"

    sha256sum --check "hubble-linux-${HUBBLE_ARCH}.tar.gz.sha256sum"
    tar xzvfC "hubble-linux-${HUBBLE_ARCH}.tar.gz" /usr/local/bin
    rm -f hubble-linux-${HUBBLE_ARCH}.tar.gz*
    echo -e "${GREEN}Hubble CLI installed${NC}"
else
    echo -e "${GREEN}Hubble CLI already installed: $(hubble version)${NC}"
fi
echo ""

# Step 6: Wait for Cilium to be ready
echo -e "${YELLOW}Step 6: Waiting for Cilium to be ready...${NC}"
cilium status --wait
echo ""

# Step 7: Verify installation
echo -e "${YELLOW}Step 7: Verifying installation...${NC}"
echo ""

echo -e "${BLUE}Cilium Pods:${NC}"
kubectl get pods -n kube-system -l k8s-app=cilium
echo ""

echo -e "${BLUE}Hubble Pods:${NC}"
kubectl get pods -n kube-system -l k8s-app=hubble-relay
kubectl get pods -n kube-system -l k8s-app=hubble-ui
echo ""

echo -e "${BLUE}Node Status:${NC}"
kubectl get nodes
echo ""

echo "=========================================="
echo -e "${GREEN}Cilium Installation Complete!${NC}"
echo "=========================================="
echo ""
echo "Your cluster now has:"
echo "  ✓ eBPF-based networking (Cilium CNI)"
echo "  ✓ eBPF load balancing (replaces kube-proxy)"
echo "  ✓ Network flow observability (Hubble)"
echo "  ✓ Prometheus metrics"
echo "  ✓ Mutual authentication via SPIRE (mTLS)"
echo ""
echo "Next steps:"
echo ""
echo "1. Run connectivity test:"
echo "   cilium connectivity test"
echo ""
echo "2. Access Hubble UI:"
echo "   cilium hubble ui"
echo "   (Opens http://localhost:12000)"
echo ""
echo "3. Watch network flows:"
echo "   cilium hubble port-forward &"
echo "   hubble observe --follow"
echo ""
echo "4. Apply network policies:"
echo "   kubectl apply -f ../policies/"
echo ""
