provider "aws" {
  region = var.aws_region
}

terraform {
  backend "s3" {
    bucket  = "orcd-terraform-state"
    key     = "prod/vector/buckets/terraform.tfstate"
    region  = "us-east-1"
    encrypt = "true"
  }
}

module "bucket" {
  for_each = var.asset_types
  source   = "git@github.com:theorchard/terraform-s3.git//modules/s3_bucket?ref=3.13.0"

  env                = var.environment
  bucket_name        = "${var.service_name}-physical-location-${var.physical_location_id}-${each.value}"
  application_family = var.application_family
  additional_tags    = var.additional_tags

  apply_server_side_encryption_by_default = {
    sse_algorithm = "AES256"
  }

  # Archive noncurrent versions of objects after 30 days unless there is an override config in the locals.
  lifecycle_rules_options_noncurrent_version_expiration = lookup(
    local.lifecycle_rules_options_noncurrent_version_expiration,
    each.value,
    [
      {
        prefix  = ""
        enabled = true
        days    = 30
      }
    ]
  )

  # Don't archive current versions unless there is an override config in the locals.
  lifecycle_rules_options_current_version_expiration = lookup(
  local.lifecycle_rules_options_current_version_expiration, each.value, [])

  lifecycle_rules_options_current_version_transition = [
    {
      prefix        = ""
      enabled       = true
      days          = 0
      storage_class = "INTELLIGENT_TIERING"
    }
  ]
}

data "aws_iam_policy_document" "bucket_read_only_policy" {
  for_each = module.bucket

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

    resources = [
      each.value.s3_bucket_arn_output,
    ]
  }

  statement {
    actions = [
      "s3:GetObject",
      "s3:GetObjectVersion",
    ]

    resources = [
      "${each.value.s3_bucket_arn_output}/*",
    ]
  }
}

resource "aws_iam_policy" "bucket_read_only_policy" {
  for_each = module.bucket

  name   = "S3-${each.value.s3_bucket_name_output}-RO"
  policy = data.aws_iam_policy_document.bucket_read_only_policy[each.key].json
}

data "aws_iam_policy_document" "bucket_read_write_policy" {
  for_each = module.bucket

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

    resources = [
      each.value.s3_bucket_arn_output,
    ]
  }

  statement {
    actions = [
      "s3:AbortMultipartUpload",
      "s3:DeleteObject",
      "s3:GetObject",
      "s3:GetObjectVersion",
      "s3:PutObject",
    ]

    resources = [
      "${each.value.s3_bucket_arn_output}/*",
    ]
  }
}

resource "aws_iam_policy" "bucket_read_write_policy" {
  for_each = module.bucket

  name   = "S3-${each.value.s3_bucket_name_output}-RW"
  policy = data.aws_iam_policy_document.bucket_read_write_policy[each.key].json
}

locals {
  lifecycle_rules_options_noncurrent_version_expiration = {}
  lifecycle_rules_options_current_version_expiration = {
    "direct-delivery" = [
      {
        prefix  = ""
        enabled = true
        days    = 30
      }
    ]
  }
}
