#!/bin/bash
set -e

echo "=== Setting up kubectl ==="

# 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 from environment variable
echo "Configuring kubeconfig..."
mkdir -p ~/.kube

# Target the PROD-account UAT cluster (489176460030).
# Both dev and prod accounts have a cluster named "uat" — the AWS account
# credentials (CircleCI context) determine which one we connect to.
# This job MUST run under devops-mgt-prod. The guard below fails loudly otherwise.
EKS_ACCOUNT_ID="489176460030"
CLUSTER_NAME="uat"
AWS_REGION="${AWS_REGION:-ca-central-1}"

CURRENT_ACCOUNT=$(aws sts get-caller-identity --query Account --output text)
if [ "${CURRENT_ACCOUNT}" != "${EKS_ACCOUNT_ID}" ]; then
    echo "❌ Wrong AWS account! Expected ${EKS_ACCOUNT_ID}, got ${CURRENT_ACCOUNT}"
    echo "   Ensure the deploy job uses the 'devops-mgt-prod' CircleCI context."
    exit 1
fi
echo "✅ Prod-account credentials verified (${CURRENT_ACCOUNT})"

EKS_ROLE_ARN="arn:aws:iam::${EKS_ACCOUNT_ID}:role/eksAdmin"
echo "Getting kubeconfig for cluster: ${CLUSTER_NAME} (role: ${EKS_ROLE_ARN})"
aws eks update-kubeconfig --region ${AWS_REGION} --name ${CLUSTER_NAME} --role-arn ${EKS_ROLE_ARN}


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

# Ensure redtag namespace exists
if ! kubectl get namespace redtag &> /dev/null; then
    echo "Creating redtag namespace..."
    kubectl create namespace redtag
else
    echo "redtag 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 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

# Configure AWS credentials for SOPS/KMS decryption
echo "Configuring AWS credentials for SOPS/KMS decryption..."

# SOPS needs AWS credentials to decrypt secrets encrypted with KMS
# KMS Key: arn:aws:kms:ca-central-1:594765360358:key/e558a999-9f99-432e-9d6b-73f06de7d1a7
# Local runner uses IRSA - pod service account automatically assumes IAM role with KMS permissions

# Export AWS credentials for SOPS
export AWS_REGION="${AWS_REGION:-ca-central-1}"

# Disable AWS profile from .sops.yaml - use environment credentials instead
# This is necessary because CircleCI doesn't have the 'tbi-dev' SSO profile configured
# Local runner: Uses IRSA credentials from pod service account
# Cloud runner: Uses credentials from CircleCI context
unset AWS_PROFILE

# Test SOPS access (optional - for debugging)
echo "Testing SOPS/KMS access..."
echo "AWS Region: ${AWS_REGION}"
echo "AWS Account ID: $(aws sts get-caller-identity --query Account --output text)"

echo "=== kubectl and helm-secrets setup complete ==="
