#!/usr/bin/env bash

set -euo pipefail

# Clean up the kubeconfig so entrypoint.sh scripts can be executed again
[ -e ${HOME}/.kube/config ] && rm ${HOME}/.kube/config && unset KUBECONFIG
KUBECONFIG=${HOME}/.kube/config

# garden
kubectl get secret -n garden garden-kubeconfig-for-admin --template={{'.data.kubeconfig'}} | base64 -d > garden
# infra-api
kubectl get secret -n infra api-server-kubeconfig --template={{.data.config}} | base64 -d > infra-api-kubeconfig.tmp
# rename infra-api kubeconfig username from admin to infra. because garden kubeconfig username is admin
sed 's/name: admin/name: infra/g;s/user: admin/user: infra/g' infra-api-kubeconfig.tmp > infra-api-kubeconfig && rm infra-api-kubeconfig.tmp
trap "rm garden" EXIT
trap "rm infra-api-kubeconfig" EXIT
KUBECONFIG=${KUBECONFIG}:garden:infra-api-kubeconfig kubectl config view --flatten > merged-kubeconfig && mv merged-kubeconfig ${KUBECONFIG}
echo "GARDEN Infra-api context ready."

export KUBECONFIG=${KUBECONFIG}

function merge_secret() {
  namespace=$1
  name=$2
  secret=$3
  kubectl --context garden -n ${namespace} get secret $secret --template={{'.data.kubeconfig'}} | base64 -d > $name || (echo "cannot get secret ${secret}" && exit 0)

  # only rename context when kubeconfig file size greater than 0
  if [ -s $name ]; then
    # clean up tempfile
    trap "rm $name" RETURN
    # better naming
    KUBECONFIG=$name kubectl config rename-context $(KUBECONFIG=$name kubectl config current-context) $name > /dev/null
    # merge
    KUBECONFIG=${KUBECONFIG}:$name kubectl config view --flatten > merged-kubeconfig && mv merged-kubeconfig ${KUBECONFIG}
  fi
}

# seeds
seeds=$(kubectl --context garden get secret -n garden --no-headers -o custom-columns=":metadata.name" | grep 'seed$')
for seed in ${seeds}; do
  merge_secret "garden" $seed $seed
  echo "SEED ${seed} context ready"
done

# shoots
projects=$(kubectl --context garden get ns --no-headers -o custom-columns=":metadata.name" | grep 'garden-')
for project in ${projects}; do
  shoots=$(kubectl --context garden get shoot -n ${project} --no-headers -o custom-columns=":metadata.name")
  for shoot in ${shoots}; do
    # append details in favor of searching tenant and region using fzf
    seed_detail=$(kubectl --context garden get shoot -n ${project} $shoot --template='{{.spec.seedName}}-{{.metadata.labels.tenant}}')
    shoot_name="${project}-${shoot}-${seed_detail}"
    merge_secret ${project} ${shoot_name} "${shoot}.kubeconfig"
    # do not print shoot details in log, simply use shoot
    echo "SHOOT ${shoot} context ready"
  done
done

# cockpit pod have AWS_WEB_IDENTITY_TOKEN_FILE and AWS_ROLE_ARN env.
defaultAccountID=$(aws sts get-caller-identity --query "Account" --output text)
# init aws config
aws configure set role_arn ${AWS_ROLE_ARN} --profile default
aws configure set web_identity_token_file /var/run/secrets/eks.amazonaws.com/serviceaccount/token --profile default

aws configure set region us-west-2 --profile dbaas-dev
aws configure set source_profile default --profile dbaas-dev
aws configure set role_arn arn:aws:iam::${defaultAccountID}:role/full-manager-service-role --profile dbaas-dev
aws configure set external_id 123 --profile dbaas-dev

function addAWSConfig() {
  accountID=$1
  profile_name=${accountID:0-4:4}

  aws configure set region us-west-2 --profile "${profile_name}"
  aws configure set source_profile default --profile "${profile_name}"
  aws configure set role_arn "arn:aws:iam::${accountID}:role/full-manager-service-role" --profile "${profile_name}"
}

profiles=(dbaas-dev)

# Add dataplane's account ID here
awsAccounts=("143458967504")

for acct in "${awsAccounts[@]}"
do
  addAWSConfig $acct
  profiles+=("${accountID:0-4:4}")
done

# get all eks kubeconfigs
function awsKubeConfig() {
  # if eks state is not active, fetch kubeconfig will failed, we should ignore error continue fetch other kubeconfig.
  aws eks --region $1 --output text list-clusters --profile $2 | awk '{print $2}' | xargs -n 1 -I {} aws eks --region $1 update-kubeconfig --name {} --profile $2 || (echo "failed fetch kubeconfig, cluster status not active" && exit 0)
}

awsRegions=(us-west-2 us-east-1 ap-northeast-1 ap-northeast-2 ap-south-1 ap-southeast-1 ap-southeast-3 eu-central-1)

for profile in "${profiles[@]}"
do
  for region in "${awsRegions[@]}"
  do
    awsKubeConfig $region $profile
  done
done

echo "all context initialized"

bash
