#!/bin/bash
set -e

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

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

# Deploy to the DEV-account cluster named "uat" (594765360358).
# Access+ UAT, the dashboard UAT, and DNS for
# tbi-rlv-cruise-content-service.uat.tbidevelopment.ca all live on that cluster.
# The prod account (489176460030) also has a cluster named "uat" (Redtag UAT).
# This job MUST run under the devops-mgt context. Pinning the cluster name is
# not enough: the same name exists in both accounts, and a second copy shares
# the OpenSearch index, so its 2 AM FTP reindex would wipe cruise-line flags.
EKS_ACCOUNT_ID="594765360358"
CLUSTER_NAME="${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} (devops-mgt), got ${CURRENT_ACCOUNT}"
    echo "Do not deploy this service with devops-mgt-prod. That lands on the Redtag UAT cluster."
    exit 1
fi
echo "Dev-account credentials verified (${CURRENT_ACCOUNT})"

# --alias names the kubeconfig context "${CLUSTER_NAME}" (e.g. "uat") so that the
# later "kubectl --context uat" / "helm --kube-context uat" calls in
# deploy-services.sh resolve. Without it, update-kubeconfig names the context
# after the full cluster ARN and those commands fail with:
#   error: context "uat" does not exist
aws eks update-kubeconfig --region ${AWS_REGION} --name ${CLUSTER_NAME} --alias ${CLUSTER_NAME}

kubectl --context ${CLUSTER_NAME} cluster-info

NAMESPACE="redtag"
if ! kubectl get namespace ${NAMESPACE} &> /dev/null; then
    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

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