locals {
  # Technically, we don't need these in ARN format, but it makes updates slightly clearer
  accounts = [ for a in var.account_list: "arn:${var.aws_partition}:iam::${a}:root" ]
}

resource "aws_s3_bucket" "bucket" {
  bucket = var.name
  acl    = "private"

  versioning {
    enabled = false
  }

  tags = merge(var.standard_tags, var.tags)

  # FIXME: Does this keep a cross-account dependency?
  #logging {
  #  target_bucket = "dps-s3-logs"
  #  target_prefix = "aws_terraform_s3_state_access_logs/"
  #}

  lifecycle_rule {
    enabled                                = true
    prefix                                 = ""
    abort_incomplete_multipart_upload_days = 7

    expiration {
      days                         = 0
      expired_object_delete_marker = false
    }
  }

  server_side_encryption_configuration {
    rule {
      apply_server_side_encryption_by_default {
        kms_master_key_id = aws_kms_key.bucketkey.arn
        sse_algorithm     = "aws:kms"
      }
    }
  }

}

resource "aws_s3_bucket_public_access_block" "public_access_block" {
  bucket                  = aws_s3_bucket.bucket.id
  block_public_acls       = true
  block_public_policy     = true
  ignore_public_acls      = true
  restrict_public_buckets = true
}

resource "aws_s3_bucket_policy" "policy" {
  bucket = aws_s3_bucket.bucket.id

  policy = <<POLICY
{
  "Version": "2012-10-17",
  "Id": "AllowAllAccounts",
  "Statement": [
    {
      "Sid": "AccountAllow",
      "Effect": "Allow",
      "Principal": {
        "AWS": ${jsonencode(local.accounts)}
      },
      "Action": [
        "s3:GetObject",
        "s3:ListBucket"
      ],
      "Resource": [
        "${aws_s3_bucket.bucket.arn}",
        "${aws_s3_bucket.bucket.arn}/*"
      ]
    }
  ]
}
POLICY
}
