terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 5.0"
    }
  }
}

provider "aws" {
  region = "us-east-1"
}

variable "oidc_arn" {
  type = string
}

variable "role_name" {
  type = string
}

variable "service_accounts" {
  type = list(string)
}

variable "policy_document" {
  type = string # json encoded string
}

variable "auto_deploy_owner_tag" {
  type = string
}

locals {
  oidc_provider_url = split("oidc-provider/", var.oidc_arn)[1]
}

resource "aws_iam_role" "controlplane_role" {
  name = var.role_name

  assume_role_policy = jsonencode({
    Version = "2012-10-17"
    Statement = [
      {
        Action = "sts:AssumeRoleWithWebIdentity"
        Effect = "Allow"
        Principal = {
          Federated = var.oidc_arn
        }
        Condition = {
          "StringEquals" = {
            "${local.oidc_provider_url}:sub" = [for service in var.service_accounts : "system:serviceaccount:${service}"]
          }
        }
      }
    ]
  })
  tags = {
    "tidbcloud-auto-deploy-owner" = var.auto_deploy_owner_tag,
  }
}

resource "aws_iam_role_policy" "controlplane_role_policy" {
  name = var.role_name
  role = aws_iam_role.controlplane_role.id

  policy = var.policy_document
}

output "controlplane_role_arn" {
  value = aws_iam_role.controlplane_role.arn
}
