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

local_output=/tmp/output.yaml
remote_output=$(yq '.outputPath' "${local_config}")
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}")
sns_topic_arn=$(yq '.jobOptions.o11yRegion.snsTopicArn' "${local_config}")
echo "cloud_provider: $cloud_provider"
echo "region: $region"
echo "logical_region_name: $logical_region_name"
echo "env: $env"
echo "account_id: $account_id"
echo "sns_topic_arn: $sns_topic_arn"

remote_dms_config=$(yq '.jobOutput.o11y-basic-dms' "${local_config}")
local_dms_config=/tmp/dms-config.yaml
if [[ "$remote_dms_config" == "null" ]]; then
    echo "No DMS configuration found in the job output."
    exit 0
fi
aws s3 cp ${remote_dms_config} ${local_dms_config} --region=$output_bucket_region

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}")

alarm_name=$(yq '.cloudwatchAlarmName' "${local_dms_config}")
sns_policy_id=$(yq '."snsPolicyId"' "${local_dms_config}")

o11y_deploy_role_arn=$(yq '.jobOptions.o11yRegion.deployRoleArn' "${local_config}")
setup_o11y_deploy_profile "$o11y_deploy_role_arn"

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

# Delete CloudWatch Alarm if exists
if aws --profile $account_id cloudwatch describe-alarms --alarm-names "$alarm_name" &> /dev/null; then
    aws --profile $account_id cloudwatch delete-alarms --alarm-names "$alarm_name"
fi

# Update SNS Policy to remove the alarm policy
# Get existing policy
existing_policy=$(aws --profile o11y-deploy sns get-topic-attributes --region us-west-2 --topic-arn "${sns_topic_arn}" --query "Attributes.Policy" --output text)

# Only update if policy exists and is not empty
if [ "$existing_policy" != "None" ] && [ -n "$existing_policy" ]; then
  # Remove the statement with the specified Sid using jq
  updated_policy=$(echo "$existing_policy" | jq --arg sid "$sns_policy_id" '
    .Statement |= map(select(.Sid != $sid))
  ')

  # Only update if there are remaining statements or if we need to clean up
  statement_count=$(echo "$updated_policy" | jq '.Statement | length')
  if [ "$statement_count" -gt 0 ]; then
    # Apply updated policy with remaining statements
    aws --profile o11y-deploy sns set-topic-attributes \
      --region us-west-2 \
      --topic-arn "${sns_topic_arn}" \
      --attribute-name Policy \
      --attribute-value "$updated_policy"
  else
    # Remove policy entirely if no statements remain
    aws --profile o11y-deploy sns set-topic-attributes \
      --region us-west-2 \
      --topic-arn "${sns_topic_arn}" \
      --attribute-name Policy \
      --attribute-value ""
  fi
else
  echo "No existing SNS policy found or policy is empty"
fi
