#!/bin/bash
set -e

echo "=== Setting up kubectl and helm-secrets ==="

# 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

# Update kubeconfig for the target cluster
aws eks update-kubeconfig --region ${AWS_REGION} --name ${CLUSTER_NAME}

# Verify kubectl connection
kubectl config current-context
kubectl get nodes --no-headers | wc -l | xargs echo "Connected to cluster with nodes:"

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

# Install helm-s3 plugin for S3 Helm repository management
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 helm-s3 plugin for S3 Helm repository management
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 for helm-secrets
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

# Verify helm-secrets installation
helm secrets --help > /dev/null && echo "✓ helm-secrets is ready"

echo "✓ kubectl and helm-secrets setup complete"
