#!/usr/bin/env bash

set -x
set -euo pipefail

ROOT=$(cd $(dirname "${BASH_SOURCE[0]}") && pwd)
source ${ROOT}/../lib.sh

remote_config=${CONFIG_PATH}
local_config=/tmp/base-config.yaml
bucket_name=${remote_config#s3://}
bucket_name=${bucket_name%%/*}
output_bucket_region=$(aws s3api get-bucket-location --bucket=$bucket_name --query="LocationConstraint" \
  --region=us-west-2 --output=text --no-cli-pager)
aws s3 cp ${remote_config} ${local_config} --region=$output_bucket_region

cloud_provider=$(yq '.cloudProvider' "${local_config}")
region=$(yq '.region' "${local_config}")
logical_region_name=$(yq '.name' "${local_config}")
env=$(yq '.env' "${local_config}")
account_id=$(yq -r -ojson '.aws.dataplaneAccounts.0' "${local_config}")

o11y_eks_remote_output=$(yq '.jobOutput.o11y-eks' "${local_config}")
o11y_eks_local_output=/tmp/o11y-eks-output.yaml
aws s3 cp ${o11y_eks_remote_output} ${o11y_eks_local_output}  --region=$output_bucket_region
cluster_name=$(yq '.cluster_name' "${o11y_eks_local_output}")

if ! eks_exists "$cluster_name" "$region" "$account_id"; then
  echo "EKS cluster $cluster_name already deleted, skip finalizer"
  exit 0
fi

oidc_issuer_url=$(yq '.cluster_oidc_issuer_url' "${o11y_eks_local_output}")
oidc_issuer=${oidc_issuer_url#https://}
oidc_issuer_arn="arn:aws:iam::${account_id}:oidc-provider/${oidc_issuer}"
echo "oidc_issuer_url: $oidc_issuer_url"
echo "oidc_issuer: $oidc_issuer"
echo "oidc_issuer_arn: $oidc_issuer_arn"

role_name=$(yq '.jobOptions.o11yRegion.roleName' "${local_config}")
policy_doc=$(aws iam get-role \
  --profile $account_id \
  --role-name "$role_name" \
  --query "Role.AssumeRolePolicyDocument" \
  --output json)

if echo "$policy_doc" | jq -e --arg oidc "$oidc_issuer_arn" \
  '.Statement[]?.Principal.Federated? | (if type=="string" then [.] else . end) | index($oidc)' >/dev/null; then
  echo "Remove OIDC provider from trust relationship..."
  new_policy=$(echo "$policy_doc" | jq --arg oidc "$oidc_issuer_arn" '
    .Statement |= map(select(
        (.Principal.Federated != $oidc)
        ))
    ')
  aws iam update-assume-role-policy \
    --profile $account_id \
    --role-name "$role_name" \
    --policy-document "$new_policy"
else
  echo "OIDC provider not found in trust relationship."
fi

# aws cloudformation delete-stack \
#   --profile $account_id \
#   --region $region \
#   --stack-name auto-deploy-$cluster_name-iam-dataplane
# aws cloudformation wait stack-delete-complete \
#   --profile $account_id \
#   --region $region \
#   --stack-name auto-deploy-$cluster_name-iam-dataplane

# aws cloudformation delete-stack \
#   --profile $account_id \
#   --region $region \
#   --stack-name auto-deploy-$cluster_name-iam
# aws cloudformation wait stack-delete-complete \
#   --profile $account_id \
#   --region $region \
#   --stack-name auto-deploy-$cluster_name-iam
