#!/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).
# DNS for tbi-rlv-insurance-service.uat.tbidevelopment.ca points at that
# cluster's load balancer. UAT booking path calls that hostname.
# The prod account (489176460030) also has a cluster named "uat". Its ingress
# for this hostname has no load balancer, so a deploy there does not serve traffic.
# This job MUST run under the devops-mgt context.
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 cluster does not serve the UAT hostname."
    exit 1
fi
echo "Dev-account credentials verified (${CURRENT_ACCOUNT})"

# --alias names the kubeconfig context "${CLUSTER_NAME}" so later kubectl and
# helm calls resolve. Without it, update-kubeconfig names the context after the
# cluster ARN.
aws eks update-kubeconfig --region ${AWS_REGION} --name ${CLUSTER_NAME} --alias ${CLUSTER_NAME}
kubectl --context ${CLUSTER_NAME} cluster-info

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