#!/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}")
resource_owner_tag=$(yq '.jobOptions.resourceOwnerTag' "${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"

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

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

# 1. Create IAM role
# No longer needed

# 2. append access policy to the o11y sns topic
# Update SNS Policy to add 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)

# If no existing policy, use empty policy structure
if [ "$existing_policy" = "None" ] || [ -z "$existing_policy" ]; then
  existing_policy='{"Version":"2008-10-17","Id":"","Statement":[]}'
fi

# Create new statement for CloudWatch alarms
new_statement=$(cat <<EOF
{
  "Sid": "${account_id}-${cluster_name}-sns",
  "Effect": "Allow",
  "Principal": {
    "AWS": "*"
  },
  "Action": [
    "SNS:Publish"
  ],
  "Resource": "${sns_topic_arn}",
  "Condition": {
    "ArnLike": {
      "aws:SourceArn": "arn:aws:cloudwatch:${region}:${account_id}:alarm:*"
    }
  }
}
EOF
)

# Merge policies using jq - remove any existing statement with same Sid, then add new one
updated_policy=$(echo "$existing_policy" | jq --argjson new_stmt "$new_statement" '
  .Statement |= map(select(.Sid != $new_stmt.Sid)) + [$new_stmt] |
  .Id = "'${account_id}-${cluster_name}'-sns"
')

# Apply updated policy
aws --profile o11y-deploy sns set-topic-attributes \
    --region us-west-2 \
    --topic-arn "${sns_topic_arn}" \
    --attribute-name "Policy" \
    --attribute-value "$updated_policy"

# 3. Create CloudWatch Alarms
aws --profile $account_id cloudwatch put-metric-alarm \
    --region us-west-2 \
    --alarm-name "WatchdogDown-${cluster_name}" \
    --alarm-description "Alarm for ${cluster_name}, triggered if deadmanswatch is down" \
    --namespace "DeadMansWatch" \
    --metric-name "Watchdog" \
    --comparison-operator "LessThanThreshold" \
    --alarm-actions "${sns_topic_arn}" \
    --threshold 1 \
    --evaluation-periods 5 \
    --period 60 \
    --statistic "Maximum" \
    --treat-missing-data "breaching" \
    --dimensions "Name=source,Value=${cluster_name}" "Name=environment,Value=${env}" "Name=scope,Value=self-monitoring" \
    --tags "Key=tidbcloud-auto-deploy-owner,Value=${resource_owner_tag}"

aws --profile $account_id cloudwatch put-metric-alarm \
    --region us-west-2 \
    --alarm-name "AlertmanagerClusterFailedToSendAlerts-${cluster_name}" \
    --alarm-description "Alarm for ${cluster_name}, triggered if alertmanager cluster failed to send alerts to jiralert" \
    --namespace "DeadMansWatch" \
    --metric-name "AlertmanagerClusterFailedToSendAlerts" \
    --comparison-operator "GreaterThanOrEqualToThreshold" \
    --alarm-actions "${sns_topic_arn}" \
    --threshold 1 \
    --evaluation-periods 1 \
    --period 120 \
    --statistic "SampleCount" \
    --treat-missing-data "notBreaching" \
    --dimensions "Name=source,Value=${cluster_name}" "Name=environment,Value=${env}" "Name=scope,Value=self-monitoring" \
    --tags "Key=tidbcloud-auto-deploy-owner,Value=${resource_owner_tag}"

local_output=/tmp/output.yaml
remote_output=$(yq '.outputPath' "${local_config}")
cat <<EOF > "${local_output}"
cloudwatchAlarmName: "WatchdogDown-${cluster_name}"
snsPolicyId: "${account_id}-${cluster_name}-sns"
EOF
echo "Write output to S3..."
aws s3 cp "${local_output}" "${remote_output}" --region=$output_bucket_region

