#!/bin/bash
set -e

echo "=== Setting up kubectl for Blue Rewards (DEV/UAT) ==="

# Install kubectl if not already installed
if ! command -v kubectl &> /dev/null; then
    echo "Installing kubectl..."
    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
else
    echo "kubectl already installed"
    kubectl version --client
fi

# Setup kubeconfig
echo "Configuring kubeconfig..."
mkdir -p ~/.kube

EKS_CLUSTER_NAME="${EKS_CLUSTER_NAME:-tbi-dev-cluster}"
AWS_REGION="${AWS_REGION:-ca-central-1}"

if [ -z "${EKS_CLUSTER_NAME}" ]; then
    echo "ERROR: EKS_CLUSTER_NAME environment variable is not set!"
    exit 1
fi

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

# Verify connection
echo "Verifying kubectl connection..."
kubectl cluster-info

# Ensure namespace exists
NAMESPACE="${DEPLOY_NAMESPACE:-redtagbluerewards}"
if ! kubectl get namespace ${NAMESPACE} &> /dev/null; then
    echo "Creating ${NAMESPACE} namespace..."
    kubectl create namespace ${NAMESPACE}
else
    echo "${NAMESPACE} namespace already exists"
fi

# Install helm-secrets plugin
echo "Installing helm-secrets plugin..."
if ! helm plugin list | grep -q secrets; then
    helm plugin install https://github.com/jkroepke/helm-secrets --version v4.5.1
else
    echo "helm-secrets plugin already installed"
fi

# Install helm-s3 plugin
echo "Installing helm-s3 plugin..."
if ! helm plugin list | grep -q s3; then
    helm plugin install https://github.com/hypnoglow/helm-s3.git
else
    echo "helm-s3 plugin already installed"
fi

# Install SOPS
echo "Installing sops..."
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
else
    echo "sops already installed"
    sops --version
fi

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

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