locals {
  starter_remote_eks_cluster_role_name  = "cp9-${local.session_name}-starter-eks-cluster"
  starter_remote_eks_node_role_name     = "cp9-${local.session_name}-starter-eks-node"
  starter_remote_eks_workload_role_name = "cp9-${local.session_name}-starter-eks-workload"
  starter_remote_eks_ebs_csi_role_name  = "cp9-${local.session_name}-starter-eks-ebs-csi"
  starter_remote_aws_lbc_role_name      = "${local.session_name}-aws-lbc"
  starter_remote_autoscaler_role_name   = "${local.session_name}-cluster-autoscaler"
  starter_remote_eks_nodegroup_name     = "cp9-${local.session_name}-starter-ng"
  starter_remote_eks_minimal_node_groups = local.starter_remote_eks_enabled ? {
    for group in local.starter_remote_eks_node_groups : group.name => group
  } : {}
  starter_remote_eks_minimal_nodegroup_names = {
    for group in local.starter_remote_eks_node_groups :
    group.name => substr("${local.session_name}-${group.name}", 0, 63)
  }
  starter_remote_eks_minimal_asg_tags = {
    for item in flatten([
      for group_name in keys(local.starter_remote_eks_minimal_node_groups) : [
        for tag_key, tag_value in merge(local.common_tags, {
          Name                                                                 = local.starter_remote_eks_minimal_nodegroup_names[group_name]
          "k8s.io/cluster-autoscaler/enabled"                                  = "true"
          "k8s.io/cluster-autoscaler/${local.starter_remote_eks_cluster_name}" = "owned"
          }) : {
          group_name = group_name
          key        = tag_key
          value      = tag_value
        }
      ]
    ]) : "${item.group_name}:${item.key}" => item
  }
  starter_remote_workload_pod_identities = {
    serverless-backup-restore = { namespace = "tidb-serverless", service_account = "backup-restore" }
    serverless-dm             = { namespace = "tidb-serverless", service_account = "dm" }
    fts-server                = { namespace = "tidb-admin", service_account = "fts-server" }
  }
  starter_remote_workload_irsa_subjects = [
    "system:serviceaccount:tidb-admin:cp9-starter-runtime",
    "system:serviceaccount:tidb-serverless:serverless-controller",
    "system:serviceaccount:tidb-admin:tidb-gateway",
    "system:serviceaccount:tidb-pool:access-s3-sa",
    "system:serviceaccount:vip-tidb-pool:access-s3-sa",
    "system:serviceaccount:canary-tidb-pool:access-s3-sa",
    "system:serviceaccount:canary-vip-tidb-pool:access-s3-sa",
    "system:serviceaccount:export-tidb-pool:access-s3-sa",
    "system:serviceaccount:super-vip-tidb-pool:access-s3-sa",
    "system:serviceaccount:export-super-vip-tidb-pool:access-s3-sa",
    "system:serviceaccount:export-vip-tidb-pool:access-s3-sa",
    "system:serviceaccount:canary-super-vip-tidb-pool:access-s3-sa",
    "system:serviceaccount:import-jobs:serverless-import",
    "system:serviceaccount:export-job:export-sa",
    "system:serviceaccount:observability:o11y-agent-control-server",
  ]
  starter_private_link_endpoint_sg_name = "plc-endpoint-sg-${local.starter_remote_eks_cluster_name}"
}

resource "aws_vpc" "starter_remote" {
  count = local.starter_remote_eks_enabled ? 1 : 0

  cidr_block           = "10.90.0.0/16"
  enable_dns_hostnames = true
  enable_dns_support   = true

  tags = merge(local.common_tags, {
    Name = local.starter_remote_eks_cluster_name
  })
}

resource "aws_internet_gateway" "starter_remote" {
  count = local.starter_remote_eks_enabled ? 1 : 0

  vpc_id = aws_vpc.starter_remote[0].id

  tags = merge(local.common_tags, {
    Name = local.starter_remote_eks_cluster_name
  })
}

resource "aws_route53_zone" "starter_private_link" {
  count = local.starter_remote_eks_enabled ? 1 : 0

  name          = "aws.plc.tidbcloud.com"
  comment       = local.starter_remote_eks_cluster_name
  force_destroy = true

  vpc {
    vpc_id     = aws_vpc.starter_remote[0].id
    vpc_region = local.target_region
  }

  tags = merge(local.common_tags, {
    Name   = "${local.starter_remote_eks_cluster_name}-private-link"
    env    = "staging"
    usedBy = "private-link-connection"
  })
}

resource "aws_subnet" "starter_remote" {
  count = local.starter_remote_eks_enabled ? 3 : 0

  vpc_id                  = aws_vpc.starter_remote[0].id
  cidr_block              = cidrsubnet(aws_vpc.starter_remote[0].cidr_block, 4, count.index)
  availability_zone       = element(data.aws_availability_zones.available.names, count.index)
  map_public_ip_on_launch = true

  tags = merge(local.common_tags, {
    Name = "${local.starter_remote_eks_cluster_name}-${count.index}"
    # The pinned serverless-regional-service discovers AWS endpoint-placement
    # subnets from this exact product tag. Routing remains public for the
    # short-lived cp9 substrate; this tag is a discovery contract, not a route
    # classification.
    type                              = "private"
    "kubernetes.io/role/elb"          = "1"
    "kubernetes.io/role/internal-elb" = "1"
  })
}

resource "aws_security_group" "starter_private_link_endpoint" {
  count = local.starter_remote_eks_enabled ? 1 : 0

  name        = local.starter_private_link_endpoint_sg_name
  description = "cp9 Starter MSK PrivateLink endpoint clients"
  vpc_id      = aws_vpc.starter_remote[0].id

  ingress {
    description = "MSK PrivateLink bootstrap listeners from Starter VPC"
    from_port   = 14001
    to_port     = 14100
    protocol    = "tcp"
    cidr_blocks = [aws_vpc.starter_remote[0].cidr_block]
  }

  ingress {
    description = "O11Y PrivateLink writes from Starter VPC"
    from_port   = 80
    to_port     = 80
    protocol    = "tcp"
    cidr_blocks = [aws_vpc.starter_remote[0].cidr_block]
  }

  egress {
    description = "MSK PrivateLink bootstrap listeners"
    from_port   = 14001
    to_port     = 14100
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }

  tags = merge(local.common_tags, {
    Name   = local.starter_private_link_endpoint_sg_name
    usedBy = "private-link-connection"
  })
}

resource "aws_route_table" "starter_remote" {
  count = local.starter_remote_eks_enabled ? 1 : 0

  vpc_id = aws_vpc.starter_remote[0].id

  route {
    cidr_block = "0.0.0.0/0"
    gateway_id = aws_internet_gateway.starter_remote[0].id
  }

  tags = merge(local.common_tags, {
    Name = local.starter_remote_eks_cluster_name
  })
}

resource "aws_route_table_association" "starter_remote" {
  count = local.starter_remote_eks_enabled ? 3 : 0

  subnet_id      = aws_subnet.starter_remote[count.index].id
  route_table_id = aws_route_table.starter_remote[0].id
}

data "aws_availability_zones" "available" {
  state = "available"
}

data "aws_iam_policy_document" "starter_remote_eks_cluster_assume" {
  count = local.starter_remote_eks_enabled ? 1 : 0

  statement {
    effect  = "Allow"
    actions = ["sts:AssumeRole"]

    principals {
      type        = "Service"
      identifiers = ["eks.amazonaws.com"]
    }
  }
}

resource "aws_iam_role" "starter_remote_cluster" {
  count = local.starter_remote_eks_enabled ? 1 : 0

  name                 = local.starter_remote_eks_cluster_role_name
  assume_role_policy   = data.aws_iam_policy_document.starter_remote_eks_cluster_assume[0].json
  permissions_boundary = local.starter_node_boundary_policy_arn

  tags = merge(local.common_tags, {
    Name = local.starter_remote_eks_cluster_role_name
  })
}

resource "aws_iam_role_policy_attachment" "starter_remote_cluster" {
  count = local.starter_remote_eks_enabled ? 1 : 0

  role       = aws_iam_role.starter_remote_cluster[0].name
  policy_arn = "arn:aws:iam::aws:policy/AmazonEKSClusterPolicy"
}

data "aws_iam_policy_document" "starter_remote_eks_node_assume" {
  count = local.starter_remote_eks_enabled ? 1 : 0

  statement {
    effect  = "Allow"
    actions = ["sts:AssumeRole"]

    principals {
      type        = "Service"
      identifiers = ["ec2.amazonaws.com"]
    }
  }
}

resource "aws_iam_role" "starter_remote_node" {
  count = local.starter_remote_eks_enabled ? 1 : 0

  name                 = local.starter_remote_eks_node_role_name
  assume_role_policy   = data.aws_iam_policy_document.starter_remote_eks_node_assume[0].json
  permissions_boundary = local.starter_node_boundary_policy_arn

  tags = merge(local.common_tags, {
    Name = local.starter_remote_eks_node_role_name
  })
}

resource "aws_iam_role_policy_attachment" "starter_remote_node_worker" {
  count = local.starter_remote_eks_enabled ? 1 : 0

  role       = aws_iam_role.starter_remote_node[0].name
  policy_arn = "arn:aws:iam::aws:policy/AmazonEKSWorkerNodePolicy"
}

resource "aws_iam_role_policy_attachment" "starter_remote_node_cni" {
  count = local.starter_remote_eks_enabled ? 1 : 0

  role       = aws_iam_role.starter_remote_node[0].name
  policy_arn = "arn:aws:iam::aws:policy/AmazonEKS_CNI_Policy"
}

resource "aws_iam_role_policy_attachment" "starter_remote_node_ecr" {
  count = local.starter_remote_eks_enabled ? 1 : 0

  role       = aws_iam_role.starter_remote_node[0].name
  policy_arn = "arn:aws:iam::aws:policy/AmazonEC2ContainerRegistryReadOnly"
}

resource "aws_eks_cluster" "starter_remote" {
  count = local.starter_remote_eks_enabled ? 1 : 0

  name     = local.starter_remote_eks_cluster_name
  role_arn = aws_iam_role.starter_remote_cluster[0].arn
  version  = local.starter_remote_eks_kubernetes_version

  access_config {
    authentication_mode = "API_AND_CONFIG_MAP"
  }

  vpc_config {
    subnet_ids              = aws_subnet.starter_remote[*].id
    endpoint_private_access = true
    endpoint_public_access  = true
    public_access_cidrs     = ["0.0.0.0/0"]
  }

  tags = merge(local.common_tags, {
    Name = local.starter_remote_eks_cluster_name
  })

  depends_on = [
    aws_iam_role_policy_attachment.starter_remote_cluster,
  ]
}

resource "aws_eks_access_entry" "starter_remote_controller" {
  count = local.starter_remote_eks_enabled && local.remote_ec2_k3d_enabled ? 1 : 0

  cluster_name  = aws_eks_cluster.starter_remote[0].name
  principal_arn = aws_iam_role.remote_runtime[0].arn
  type          = "STANDARD"

  tags = local.common_tags
}

resource "aws_eks_access_policy_association" "starter_remote_controller" {
  count = local.starter_remote_eks_enabled && local.remote_ec2_k3d_enabled ? 1 : 0

  cluster_name  = aws_eks_cluster.starter_remote[0].name
  principal_arn = aws_iam_role.remote_runtime[0].arn
  policy_arn    = "arn:aws:eks::aws:cluster-access-policy/AmazonEKSClusterAdminPolicy"

  access_scope {
    type = "cluster"
  }

  depends_on = [aws_eks_access_entry.starter_remote_controller]
}

resource "aws_iam_openid_connect_provider" "starter_remote" {
  count = local.starter_remote_eks_enabled ? 1 : 0

  url            = aws_eks_cluster.starter_remote[0].identity[0].oidc[0].issuer
  client_id_list = ["sts.amazonaws.com"]

  tags = merge(local.common_tags, {
    Name = "${local.starter_remote_eks_cluster_name}-oidc"
  })
}

resource "aws_eks_node_group" "starter_remote" {
  count = local.starter_remote_eks_enabled && length(local.starter_remote_eks_node_groups) == 0 ? 1 : 0

  cluster_name    = aws_eks_cluster.starter_remote[0].name
  node_group_name = local.starter_remote_eks_nodegroup_name
  node_role_arn   = aws_iam_role.starter_remote_node[0].arn
  subnet_ids      = aws_subnet.starter_remote[*].id
  instance_types  = [local.starter_remote_eks_node_instance_type]

  scaling_config {
    desired_size = local.starter_remote_eks_node_count
    min_size     = local.starter_remote_eks_node_count
    max_size     = local.starter_remote_eks_node_count + 1
  }

  labels = {
    "serverless.tidbcloud.com/node"      = "tidb"
    "serverless.tidbcloud.com/nodegroup" = local.starter_remote_eks_nodegroup_name
  }

  tags = merge(local.common_tags, {
    Name = local.starter_remote_eks_nodegroup_name
  })

  lifecycle {
    ignore_changes = [scaling_config[0].desired_size]
  }

  depends_on = [
    aws_iam_role_policy_attachment.starter_remote_node_worker,
    aws_iam_role_policy_attachment.starter_remote_node_cni,
    aws_iam_role_policy_attachment.starter_remote_node_ecr,
    aws_iam_role_policy.starter_remote_node_runtime,
  ]
}

resource "aws_eks_node_group" "starter_remote_minimal" {
  for_each = local.starter_remote_eks_minimal_node_groups

  cluster_name    = aws_eks_cluster.starter_remote[0].name
  node_group_name = local.starter_remote_eks_minimal_nodegroup_names[each.key]
  node_role_arn   = aws_iam_role.starter_remote_node[0].arn
  subnet_ids      = aws_subnet.starter_remote[*].id
  instance_types  = [each.value.instance_type]
  ami_type        = each.value.ami_type

  launch_template {
    id      = aws_launch_template.starter_remote_minimal[each.key].id
    version = aws_launch_template.starter_remote_minimal[each.key].latest_version
  }

  scaling_config {
    desired_size = each.value.desired_size
    min_size     = each.value.min_size
    max_size     = each.value.max_size
  }

  labels = merge({
    "serverless.tidbcloud.com/nodegroup" = local.starter_remote_eks_minimal_nodegroup_names[each.key]
  }, each.value.labels)

  dynamic "taint" {
    for_each = each.value.taints
    content {
      key    = taint.value.key
      value  = taint.value.value
      effect = taint.value.effect
    }
  }

  tags = merge(local.common_tags, {
    Name = local.starter_remote_eks_minimal_nodegroup_names[each.key]
  })

  lifecycle {
    ignore_changes = [scaling_config[0].desired_size]
  }

  depends_on = [
    aws_iam_role_policy_attachment.starter_remote_node_worker,
    aws_iam_role_policy_attachment.starter_remote_node_cni,
    aws_iam_role_policy_attachment.starter_remote_node_ecr,
    aws_iam_role_policy.starter_remote_node_runtime,
  ]
}

resource "aws_launch_template" "starter_remote_minimal" {
  for_each = local.starter_remote_eks_minimal_node_groups

  name_prefix            = "${local.session_name}-${each.key}-"
  update_default_version = true

  tag_specifications {
    resource_type = "instance"
    tags = merge(local.common_tags, {
      Name = local.starter_remote_eks_minimal_nodegroup_names[each.key]
    })
  }

  tag_specifications {
    resource_type = "volume"
    tags = merge(local.common_tags, {
      Name = local.starter_remote_eks_minimal_nodegroup_names[each.key]
    })
  }

  tag_specifications {
    resource_type = "network-interface"
    tags = merge(local.common_tags, {
      Name = local.starter_remote_eks_minimal_nodegroup_names[each.key]
    })
  }

  tags = merge(local.common_tags, {
    Name = local.starter_remote_eks_minimal_nodegroup_names[each.key]
  })
}

resource "aws_autoscaling_group_tag" "starter_remote_minimal" {
  for_each = local.starter_remote_eks_minimal_asg_tags

  autoscaling_group_name = aws_eks_node_group.starter_remote_minimal[each.value.group_name].resources[0].autoscaling_groups[0].name

  tag {
    key                 = each.value.key
    value               = each.value.value
    propagate_at_launch = true
  }
}

data "aws_iam_policy_document" "starter_remote_runtime_assume" {
  count = local.starter_remote_eks_enabled ? 1 : 0

  statement {
    sid     = "AllowStarterWorkloadSelfAssume"
    effect  = "Allow"
    actions = ["sts:AssumeRole"]

    principals {
      type        = "AWS"
      identifiers = ["arn:aws:iam::${data.aws_caller_identity.current.account_id}:root"]
    }

    condition {
      test     = "ArnEquals"
      variable = "aws:PrincipalArn"
      values   = ["arn:aws:iam::${data.aws_caller_identity.current.account_id}:role/${local.starter_remote_eks_workload_role_name}"]
    }
  }

  statement {
    sid     = "AllowStarterWorkloadPodIdentity"
    effect  = "Allow"
    actions = ["sts:AssumeRole", "sts:TagSession"]

    principals {
      type        = "Service"
      identifiers = ["pods.eks.amazonaws.com"]
    }

    condition {
      test     = "StringEquals"
      variable = "aws:RequestTag/eks-cluster-name"
      values   = [local.starter_remote_eks_cluster_name]
    }
  }

  statement {
    sid     = "AllowStarterWorkloadIRSA"
    effect  = "Allow"
    actions = ["sts:AssumeRoleWithWebIdentity"]

    principals {
      type        = "Federated"
      identifiers = [aws_iam_openid_connect_provider.starter_remote[0].arn]
    }

    condition {
      test     = "StringEquals"
      variable = "${trimprefix(aws_eks_cluster.starter_remote[0].identity[0].oidc[0].issuer, "https://")}:aud"
      values   = ["sts.amazonaws.com"]
    }

    condition {
      test     = "StringEquals"
      variable = "${trimprefix(aws_eks_cluster.starter_remote[0].identity[0].oidc[0].issuer, "https://")}:sub"
      values   = local.starter_remote_workload_irsa_subjects
    }
  }
}

data "aws_iam_policy_document" "starter_remote_ebs_csi_assume" {
  count = local.starter_remote_eks_enabled ? 1 : 0

  statement {
    sid     = "AllowStarterEBSCSIPodIdentity"
    effect  = "Allow"
    actions = ["sts:AssumeRole", "sts:TagSession"]

    principals {
      type        = "Service"
      identifiers = ["pods.eks.amazonaws.com"]
    }

    condition {
      test     = "StringEquals"
      variable = "aws:RequestTag/eks-cluster-name"
      values   = [local.starter_remote_eks_cluster_name]
    }

    condition {
      test     = "StringEquals"
      variable = "aws:RequestTag/kubernetes-namespace"
      values   = ["kube-system"]
    }

    condition {
      test     = "StringEquals"
      variable = "aws:RequestTag/kubernetes-service-account"
      values   = ["ebs-csi-controller-sa"]
    }
  }
}

resource "aws_iam_role" "starter_remote_workload" {
  count = local.starter_remote_eks_enabled ? 1 : 0

  name                 = local.starter_remote_eks_workload_role_name
  assume_role_policy   = data.aws_iam_policy_document.starter_remote_runtime_assume[0].json
  permissions_boundary = local.starter_node_boundary_policy_arn

  tags = merge(local.common_tags, {
    Name = local.starter_remote_eks_workload_role_name
  })
}

data "aws_iam_policy_document" "starter_remote_workload_runtime" {
  count = local.starter_remote_eks_enabled ? 1 : 0

  source_policy_documents = [data.aws_iam_policy_document.starter_remote_node_runtime[0].json]

  statement {
    sid       = "StarterCustomerStorageAssumeRole"
    effect    = "Allow"
    actions   = ["sts:AssumeRole"]
    resources = ["*"]
  }

  statement {
    sid       = "StarterKafkaServiceLinkedRoleCreate"
    effect    = "Allow"
    actions   = ["iam:CreateServiceLinkedRole"]
    resources = ["*"]

    condition {
      test     = "StringEquals"
      variable = "iam:AWSServiceName"
      values   = ["kafka.amazonaws.com"]
    }
  }
}

resource "aws_iam_role_policy" "starter_remote_workload_runtime" {
  count = local.starter_remote_eks_enabled ? 1 : 0

  name   = "cp9-starter-runtime"
  role   = aws_iam_role.starter_remote_workload[0].id
  policy = data.aws_iam_policy_document.starter_remote_workload_runtime[0].json
}

resource "aws_iam_role" "starter_remote_ebs_csi" {
  count = local.starter_remote_eks_enabled ? 1 : 0

  name                 = local.starter_remote_eks_ebs_csi_role_name
  assume_role_policy   = data.aws_iam_policy_document.starter_remote_ebs_csi_assume[0].json
  permissions_boundary = local.starter_node_boundary_policy_arn

  tags = merge(local.common_tags, {
    Name = local.starter_remote_eks_ebs_csi_role_name
  })
}

resource "aws_iam_role_policy_attachment" "starter_remote_ebs_csi" {
  count = local.starter_remote_eks_enabled ? 1 : 0

  role       = aws_iam_role.starter_remote_ebs_csi[0].name
  policy_arn = "arn:aws:iam::aws:policy/service-role/AmazonEBSCSIDriverPolicy"
}

resource "aws_eks_addon" "starter_pod_identity_agent" {
  count = local.starter_remote_eks_enabled ? 1 : 0

  cluster_name = aws_eks_cluster.starter_remote[0].name
  addon_name   = "eks-pod-identity-agent"

  tags = merge(local.common_tags, {
    Name = "${local.starter_remote_eks_cluster_name}-pod-identity-agent"
  })

  depends_on = [
    aws_eks_node_group.starter_remote,
    aws_eks_node_group.starter_remote_minimal,
  ]
}

resource "aws_eks_pod_identity_association" "starter_ebs_csi" {
  count = local.starter_remote_eks_enabled ? 1 : 0

  cluster_name    = aws_eks_cluster.starter_remote[0].name
  namespace       = "kube-system"
  service_account = "ebs-csi-controller-sa"
  role_arn        = aws_iam_role.starter_remote_ebs_csi[0].arn

  tags = merge(local.common_tags, {
    Name = "${local.starter_remote_eks_cluster_name}-ebs-csi"
  })

  depends_on = [aws_eks_addon.starter_pod_identity_agent]
}

resource "aws_eks_addon" "starter_ebs_csi_driver" {
  count = local.starter_remote_eks_enabled ? 1 : 0

  cluster_name = aws_eks_cluster.starter_remote[0].name
  addon_name   = "aws-ebs-csi-driver"

  tags = merge(local.common_tags, {
    Name = "${local.starter_remote_eks_cluster_name}-ebs-csi-driver"
  })

  depends_on = [
    aws_eks_node_group.starter_remote,
    aws_eks_node_group.starter_remote_minimal,
    aws_iam_role_policy_attachment.starter_remote_ebs_csi,
    aws_eks_pod_identity_association.starter_ebs_csi,
  ]
}

resource "aws_eks_pod_identity_association" "starter_runtime" {
  for_each = local.starter_remote_eks_enabled ? local.starter_remote_workload_pod_identities : {}

  cluster_name    = aws_eks_cluster.starter_remote[0].name
  namespace       = each.value.namespace
  service_account = each.value.service_account
  role_arn        = aws_iam_role.starter_remote_workload[0].arn

  tags = merge(local.common_tags, {
    Name = "${local.starter_remote_eks_cluster_name}-${each.key}"
  })

  depends_on = [aws_eks_addon.starter_pod_identity_agent]
}

data "aws_iam_policy_document" "starter_cluster_autoscaler_assume" {
  count = local.starter_remote_eks_enabled ? 1 : 0

  statement {
    effect  = "Allow"
    actions = ["sts:AssumeRole", "sts:TagSession"]

    principals {
      type        = "Service"
      identifiers = ["pods.eks.amazonaws.com"]
    }

    condition {
      test     = "StringEquals"
      variable = "aws:RequestTag/eks-cluster-name"
      values   = [local.starter_remote_eks_cluster_name]
    }

    condition {
      test     = "StringEquals"
      variable = "aws:RequestTag/kubernetes-namespace"
      values   = ["kube-system"]
    }

    condition {
      test     = "StringEquals"
      variable = "aws:RequestTag/kubernetes-service-account"
      values   = ["cluster-autoscaler"]
    }
  }
}

resource "aws_iam_role" "starter_cluster_autoscaler" {
  count = local.starter_remote_eks_enabled ? 1 : 0

  name                 = local.starter_remote_autoscaler_role_name
  assume_role_policy   = data.aws_iam_policy_document.starter_cluster_autoscaler_assume[0].json
  permissions_boundary = local.starter_node_boundary_policy_arn

  tags = merge(local.common_tags, {
    Name = local.starter_remote_autoscaler_role_name
  })
}

data "aws_iam_policy_document" "starter_cluster_autoscaler" {
  count = local.starter_remote_eks_enabled ? 1 : 0

  statement {
    effect = "Allow"
    actions = [
      "autoscaling:DescribeAutoScalingGroups",
      "autoscaling:DescribeAutoScalingInstances",
      "autoscaling:DescribeLaunchConfigurations",
      "autoscaling:DescribeScalingActivities",
      "autoscaling:DescribeTags",
      "autoscaling:SetDesiredCapacity",
      "autoscaling:TerminateInstanceInAutoScalingGroup",
      "ec2:DescribeImages",
      "ec2:DescribeInstanceTypes",
      "ec2:DescribeLaunchTemplateVersions",
      "ec2:GetInstanceTypesFromInstanceRequirements",
      "eks:DescribeNodegroup",
    ]
    resources = ["*"]
  }
}

resource "aws_iam_role_policy" "starter_cluster_autoscaler" {
  count = local.starter_remote_eks_enabled ? 1 : 0

  name   = "cp9-starter-cluster-autoscaler"
  role   = aws_iam_role.starter_cluster_autoscaler[0].id
  policy = data.aws_iam_policy_document.starter_cluster_autoscaler[0].json
}

resource "aws_eks_pod_identity_association" "starter_cluster_autoscaler" {
  count = local.starter_remote_eks_enabled ? 1 : 0

  cluster_name    = aws_eks_cluster.starter_remote[0].name
  namespace       = "kube-system"
  service_account = "cluster-autoscaler"
  role_arn        = aws_iam_role.starter_cluster_autoscaler[0].arn

  tags = merge(local.common_tags, {
    Name = "${local.starter_remote_eks_cluster_name}-cluster-autoscaler"
  })

  depends_on = [
    aws_eks_addon.starter_pod_identity_agent,
    aws_iam_role_policy.starter_cluster_autoscaler,
  ]
}

data "aws_iam_policy_document" "starter_aws_lbc_assume" {
  count = local.starter_remote_eks_enabled ? 1 : 0

  statement {
    effect  = "Allow"
    actions = ["sts:AssumeRole", "sts:TagSession"]

    principals {
      type        = "Service"
      identifiers = ["pods.eks.amazonaws.com"]
    }

    condition {
      test     = "StringEquals"
      variable = "aws:RequestTag/eks-cluster-name"
      values   = [local.starter_remote_eks_cluster_name]
    }

    condition {
      test     = "StringEquals"
      variable = "aws:RequestTag/kubernetes-namespace"
      values   = ["kube-system"]
    }

    condition {
      test     = "StringEquals"
      variable = "aws:RequestTag/kubernetes-service-account"
      values   = ["aws-load-balancer-controller"]
    }
  }
}

resource "aws_iam_role" "starter_aws_lbc" {
  count = local.starter_remote_eks_enabled ? 1 : 0

  name                 = local.starter_remote_aws_lbc_role_name
  assume_role_policy   = data.aws_iam_policy_document.starter_aws_lbc_assume[0].json
  permissions_boundary = local.starter_node_boundary_policy_arn

  tags = merge(local.common_tags, {
    Name = local.starter_remote_aws_lbc_role_name
  })
}

data "aws_iam_policy_document" "starter_aws_lbc" {
  count = local.starter_remote_eks_enabled ? 1 : 0

  statement {
    effect = "Allow"
    actions = [
      "acm:DescribeCertificate",
      "acm:ListCertificates",
      "cognito-idp:DescribeUserPoolClient",
      "ec2:AuthorizeSecurityGroupIngress",
      "ec2:CreateSecurityGroup",
      "ec2:CreateTags",
      "ec2:DeleteSecurityGroup",
      "ec2:DeleteTags",
      "ec2:Describe*",
      "ec2:GetCoipPoolUsage",
      "ec2:RevokeSecurityGroupIngress",
      "elasticloadbalancing:*",
      "iam:CreateServiceLinkedRole",
      "iam:GetServerCertificate",
      "iam:ListServerCertificates",
      "shield:*",
      "waf-regional:*",
      "wafv2:*",
    ]
    resources = ["*"]
  }
}

resource "aws_iam_role_policy" "starter_aws_lbc" {
  count = local.starter_remote_eks_enabled ? 1 : 0

  name   = "cp9-starter-aws-lbc"
  role   = aws_iam_role.starter_aws_lbc[0].id
  policy = data.aws_iam_policy_document.starter_aws_lbc[0].json
}

resource "aws_eks_pod_identity_association" "starter_aws_lbc" {
  count = local.starter_remote_eks_enabled ? 1 : 0

  cluster_name    = aws_eks_cluster.starter_remote[0].name
  namespace       = "kube-system"
  service_account = "aws-load-balancer-controller"
  role_arn        = aws_iam_role.starter_aws_lbc[0].arn

  tags = merge(local.common_tags, {
    Name = "${local.starter_remote_eks_cluster_name}-aws-lbc"
  })

  depends_on = [
    aws_eks_addon.starter_pod_identity_agent,
    aws_iam_role_policy.starter_aws_lbc,
  ]
}
