provider "aws" {
  region = var.aws_region
}

# Terraform backends cannot contain interpolations
terraform {
  backend "s3" {
    bucket  = "orcd-terraform-state"
    key     = "prod/iam/groups/internal-label-moves/terraform.tfstate"
    region  = "us-east-1"
    encrypt = "true"
  }
}

module "group_with_attachments" {
  source = "git@github.com:theorchard/terraform-iam-policies.git//modules/groups?ref=1.6.8"

  group_name = "internal-label-moves"
  users = [
    "astephenson",
  ]
  application_families_to_access = []
}

data "aws_s3_bucket" "buckets_to_write_access" {
  for_each = toset(keys(var.s3_buckets_to_write_access))
  bucket   = each.value
}

data "aws_iam_policy_document" "s3_policy" {
  statement {
    actions = [
      "s3:GetObject",
      "s3:PutObject",
      "s3:PutObjectTagging",
      "s3:PutObjectVersion*",
      "s3:DeleteObject*",
    ]

    resources = [for bucket in data.aws_s3_bucket.buckets_to_write_access : format("%s/%s", bucket.arn, lookup(var.s3_buckets_to_write_access, bucket.id))]
  }

  statement {
    actions = [
      "s3:ListBucket",
      "s3:Get*",
    ]

    resources = concat(
      [for bucket in data.aws_s3_bucket.buckets_to_write_access : bucket.arn],
    )
  }
}

# Creates policy for access to required S3 buckets
# AWS imposes a maximum number of policy attachments per group, otherwise we'd attach the individual per-bucket policies
# Instead, create a rollup policy representing access to all of the relevant buckets
resource "aws_iam_policy" "s3_policy" {
  name   = "S3-internal-label-moves-team-policy"
  policy = data.aws_iam_policy_document.s3_policy.json
}

resource "aws_iam_group_policy_attachment" "s3_policy_attachment" {
  group      = module.group_with_attachments.iam_group_name
  policy_arn = aws_iam_policy.s3_policy.arn
}
