#!/bin/bash
set -e

echo "=== Setting up kubectl and helm plugins ==="

if ! command -v kubectl &> /dev/null; then
    curl -LO "https://dl.k8s.io/release/$(curl -L -s https://dl.k8s.io/release/stable.txt)/bin/linux/amd64/kubectl"
    sudo install -o root -g root -m 0755 kubectl /usr/local/bin/kubectl
    rm kubectl
fi

CLUSTER_NAME="${CLUSTER_NAME:-dev}"
AWS_REGION="${AWS_REGION:-ca-central-1}"
NAMESPACE="${NAMESPACE:-helix}"

echo "Getting kubeconfig for cluster: ${CLUSTER_NAME} in region: ${AWS_REGION}"
aws eks update-kubeconfig --name "${CLUSTER_NAME}" --region "${AWS_REGION}"

kubectl cluster-info
if ! kubectl get namespace "${NAMESPACE}" &> /dev/null; then
    echo "Creating ${NAMESPACE} namespace..."
    kubectl create namespace "${NAMESPACE}"
fi

if ! helm plugin list | grep -q secrets; then
    helm plugin install https://github.com/jkroepke/helm-secrets --version v4.5.1
fi
if ! helm plugin list | grep -q s3; then
    helm plugin install https://github.com/hypnoglow/helm-s3.git
fi

if ! command -v sops &> /dev/null; then
    wget https://github.com/mozilla/sops/releases/download/v3.8.1/sops-v3.8.1.linux.amd64 -O /tmp/sops
    sudo mv /tmp/sops /usr/local/bin/sops
    sudo chmod +x /usr/local/bin/sops
fi

export AWS_REGION="${AWS_REGION:-ca-central-1}"
unset AWS_PROFILE || true

echo "AWS Account ID: $(aws sts get-caller-identity --query Account --output text)"
echo "=== kubectl and helm setup complete ==="
