resource "aws_s3_bucket" "audit_reports" {
  provider = aws.c2 # The reports go in the c2 bucket
  bucket = "xdr-ca-audit-reports"
  acl    = "private"

  versioning {
    enabled = true
  }

  # TODO: Enable S3 logging... everywhere. We don't have a C2 bucket for this.
  #logging {
  #  target_bucket = module.xdr_config_logging_bucket.s3_bucket_name
  #  target_prefix = "${var.aws_account_id}-${var.aws_region}-awsconfig/"
  #}

  lifecycle_rule {
    id = "CleanUp"
    enabled = true
    abort_incomplete_multipart_upload_days = 7
    # Clean up old versions after a year
    noncurrent_version_expiration {
      days = 365
    }
  }

  server_side_encryption_configuration {
    rule {
      apply_server_side_encryption_by_default {
        sse_algorithm = "AES256" # Default keys are fine. We don't really need encryption here.
      }
    }
  }

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

data "aws_iam_policy_document" "audit_reports_bucket_access" {
  statement {
    actions = [
      "s3:GetBucketAcl",
      "s3:GetBucketLocation",
      "s3:PutObject",
      "s3:PutObjectAcl",
    ]

    resources = [
      aws_s3_bucket.audit_reports.arn,
      "${aws_s3_bucket.audit_reports.arn}/*",
    ]

    principals {
      identifiers = ["acm-pca.amazonaws.com"]
      type        = "Service"
    }

    # TODO: Consider restricting this to the accounts, but may need to add Get permissions?
    # "Condition":{
    #       "StringEquals":{
    #          "aws:SourceAccount":"account",
    #          "aws:SourceArn":"arn:partition:acm-pca:region:account:certificate-authority/CA-ID"
    #       }
    #    }
  }
}

resource "aws_s3_bucket_policy" "audit_reports" {
  provider = aws.c2 # The reports go in the c2 bucket
  bucket = aws_s3_bucket.audit_reports.id
  policy = data.aws_iam_policy_document.audit_reports_bucket_access.json
  depends_on = [ aws_s3_bucket.audit_reports ]
}

resource "aws_s3_bucket_public_access_block" "audit_reports_bucket_block_public_access" {
  provider = aws.c2 # The reports go in the c2 bucket
  bucket                  = aws_s3_bucket.audit_reports.id
  block_public_acls       = true
  block_public_policy     = true
  ignore_public_acls      = true
  restrict_public_buckets = true
  depends_on = [ aws_s3_bucket.audit_reports ]
}
