data "aws_caller_identity" "current" {
}

data "aws_region" "current" {
}

locals {
  account_id = data.aws_caller_identity.current.account_id
  bucket_name = coalesce(
    var.bucket_name,
    "${local.account_id}-${local.region}-s3logging-${var.bucket_suffix}"
  )

  region = data.aws_region.current.name
}

resource "aws_s3_bucket" "this" {
  bucket = local.bucket_name
  acl    = "log-delivery-write"
  tags   = var.tags

  dynamic "lifecycle_rule" {
    iterator = rule
    for_each = var.lifecycle_rules

    content {
      id      = rule.value.id
      enabled = rule.value.enabled
      prefix  = lookup(rule.value, "prefix", null)
      abort_incomplete_multipart_upload_days = lookup(rule.value, "abort_incomplete_multipart_upload_days", 0)

      expiration {
        days = lookup(rule.value, "expiration", 2147483647)
      }

      noncurrent_version_expiration {
        days = lookup(rule.value, "noncurrent_version_expiration", 2147483647)
      }
    }
  }

  server_side_encryption_configuration {
    rule {
      apply_server_side_encryption_by_default {
        sse_algorithm = "aws:kms"
      }
    }
  }

  versioning {
    enabled = var.versioning_enabled
  }

  lifecycle {
    ignore_changes = [versioning[0].mfa_delete]
  }

  # Conformance Pack for CIS requires access logs on all S3 buckets and is a best
  # practice.
  #
  # Logging to the bucket itself is allowed, but if we ingest into splunk, make 
  # sure we don't set up a feedback loop (splunk accesses s3 bucket to get a log
  # which creates a log which leads to splunk accessing the s3 bucket)
  logging {
    target_bucket = local.bucket_name
    target_prefix = "${data.aws_caller_identity.current.account_id}-${data.aws_region.current.name}-${local.bucket_name}"
  }

}

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