#!/usr/bin/env bash

set -x
set -euo pipefail

ROOT=$(cd $(dirname "${BASH_SOURCE[0]}") && pwd)

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

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}")
account_id=$(yq -r -ojson '.aws.dataplaneAccounts.0' "${local_config}")

echo "cloud_provider: $cloud_provider"
echo "region: $region"
echo "logical_region_name: $logical_region_name"
echo "env: $env"
echo "cluster_name: $cluster_name"
echo "account_id: $account_id"

# oidc_issuer_url=$(aws eks describe-cluster \
#   --name $cluster_name \
#   --query 'cluster.identity.oidc.issuer' \
#   --output text)
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 "OIDC provider already exists in trust relationship."
else
  echo "Adding new OIDC provider to trust relationship..."
  add_statement=$(cat <<EOF
{
    "Effect": "Allow",
    "Principal": {
        "Federated": "${oidc_issuer_arn}"
    },
    "Action": "sts:AssumeRoleWithWebIdentity",
    "Condition": {
        "StringLike": {
            "${oidc_issuer}:sub": "system:serviceaccount:*:*",
            "${oidc_issuer}:aud": "sts.amazonaws.com"
        }
    }
}
EOF
)
  new_policy=$(echo "$policy_doc" | jq ".Statement += [$add_statement]")
  aws iam update-assume-role-policy \
    --profile $account_id \
    --role-name "$role_name" \
    --policy-document "$new_policy"
fi

# # Create customer managed polocies
# for policy_file in $ROOT/aws/policies/*.json; do
#   policy_name=$(basename "$policy_file" .json)
#   echo "Processing policy: $policy_name"

#   # Check if the policy already exists
#   if aws --profile $account_id iam get-policy --policy-arn arn:aws:iam::${account_id}:policy/${policy_name} > /dev/null 2>&1; then
#     echo "Policy ${policy_name} already exists. Skipping creation."
#   else
#     echo "Creating policy ${policy_name}..."
#     aws --profile $account_id iam create-policy \
#       --policy-name ${policy_name} \
#       --policy-document file://${policy_file}
#   fi
# done

# aws cloudformation deploy \
#   --region $region \
#   --profile $account_id \
#   --stack-name auto-deploy-$cluster_name-iam \
#   --template-file $ROOT/aws/cloudformation/iam.yaml \
#   --capabilities CAPABILITY_NAMED_IAM \
#   --parameter-overrides \
#     Env=$env \
#     Region=$region \
#     ClusterName=$cluster_name \
#     AccountId=$account_id \
#     OIDCIssuer=$oidc_issuer

# Splitted roles
#
# cat <<EOF > "${local_output}"
# loadBalancerController:
#   roleArn: arn:aws:iam::${account_id}:role/lb-controller-${cluster_name}
# externalDns:
#   roleArn: arn:aws:iam::${account_id}:role/external-dns-${cluster_name}
# awsClusterAutoscaler:
#   roleArn: arn:aws:iam::${account_id}:role/auto-scaler-${cluster_name}
# regionalServer:
#   roleArn: arn:aws:iam::${account_id}:role/regional-server-${cluster_name}
# loki:
#   roleArn: arn:aws:iam::${account_id}:role/loki-${cluster_name}
# vmbackup:
#   roleArn: arn:aws:iam::${account_id}:role/vmbackup-${cluster_name}
# alertManager:
#   roleArn: arn:aws:iam::${account_id}:role/self-alertmanager-${cluster_name}
# o11yBackup:
#   roleArn: arn:aws:iam::${account_id}:role/o11y-backup-${cluster_name}
# EOF

# Unified role
#

o11y_control_plane_role="arn:aws:iam::${account_id}:role/${role_name}"
cat <<EOF > "${local_output}"
loadBalancerController:
  roleArn: ${o11y_control_plane_role}
externalDns:
  roleArn: ${o11y_control_plane_role}
awsClusterAutoscaler:
  roleArn: ${o11y_control_plane_role}
regionalServer:
  roleArn: ${o11y_control_plane_role}
loki:
  roleArn: ${o11y_control_plane_role}
vmbackup:
  roleArn: ${o11y_control_plane_role}
alertManager:
  roleArn: ${o11y_control_plane_role}
o11yBackup:
  roleArn: ${o11y_control_plane_role}
EOF

echo "Write output to S3..."
aws s3 cp "${local_output}" "${remote_output}" --region=$output_bucket_region
