#!/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

# This folder deploys to the uat cluster. The devops-mgt CircleCI context
# exports CLUSTER_NAME=dev, and ${CLUSTER_NAME:-uat} kept that value, so
# uat-branch deploys landed on the dev cluster.
CLUSTER_NAME="uat"
export CLUSTER_NAME
if [ -n "${BASH_ENV:-}" ]; then
    echo 'export CLUSTER_NAME=uat' >> "${BASH_ENV}"
fi
AWS_REGION="${AWS_REGION:-ca-central-1}"

aws eks update-kubeconfig --name ${CLUSTER_NAME} --region ${AWS_REGION}
kubectl cluster-info

NAMESPACE="gigi"
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 ==="
