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

variable "oidc" {
  type = string
}

variable "controlplane_account" {
  type = string
}

variable "role_name" {
  type = string
}

variable "service_account" {
  type = string
}

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

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 = "arn:aws:iam::${var.controlplane_account}:oidc-provider/${var.oidc}"
        }
        Condition = {
          "StringLike" = {
            "${var.oidc}:aud" = "sts.amazonaws.com"
            "${var.oidc}:sub" = "system:serviceaccount:*:${var.service_account}"
          }
        }
      }
    ]
  })
}

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
}
