locals {
  bucket_name = "xdr-${ var.splunk_prefix }-${ var.environment }-splunk-frozen"
  accounts = [ var.aws_account_id ]
  account_arns = [ for a in local.accounts: "arn:${var.aws_partition}:iam::${a}:root" ]
}

resource "aws_s3_bucket" "bucket" {
  bucket = local.bucket_name
  acl    = "private"

  versioning {
    enabled = false
  }

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

  #logging {
  #  target_bucket = "dps-s3-logs"
  #  target_prefix = "aws_terraform_s3_state_access_logs/"
  #}

  lifecycle_rule {
    id      = "GLACIER"
    enabled = true

    abort_incomplete_multipart_upload_days = 2

    transition {
      days          = 3
      storage_class = "GLACIER"
    }

    expiration {
      days = 365
    }
  }

  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

  # Not technically dependent, but prevents a "Conflicting conditional operation" conflict.
  # See https://github.com/hashicorp/terraform-provider-aws/issues/7628
  depends_on = [ aws_s3_bucket_policy.policy ] 
}

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

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