provider "aws" {
  region = var.aws_region
}

# Terraform backends cannot contain interpolations
terraform {
  backend "s3" {
    bucket  = "orcd-terraform-state"
    key     = "prod/iam/groups/integrations/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.18.2"

  group_name = "integrations"
  users = [
    "aoshomoji",
    "bburton",
    "dkirch",
    "gquintino",
    "lvona",
    "nlichtenstein",
    "rkordisch",
    "shlee",
    "wcheong",
  ]
  application_families_to_access = [
    "integrations",
  ]

    iam_roles_to_access = [
    "arn:aws:iam::989790945997:role/integrations-role",
    "arn:aws:iam::375914681009:role/integrations-role"
  ]
}

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

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:Get*",
    ]

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

  statement {
    actions = [
      "s3:AbortMultipartUpload",
      "s3:CreateMultipartUpload",
      "s3:CompleteMultipartUpload",
      "s3:ListMultipartUploads",
      "s3:PutObject*",
      "s3:DeleteObject*",
      "s3:UploadPart*",
      "s3:ListParts",
    ]

    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:ListObjects",
      "s3:Get*",
      "s3:Head*",
    ]

    resources = concat(
      [for bucket in data.aws_s3_bucket.buckets_to_read_access : bucket.arn],
      [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-integrations-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
}
