# Copy files into the bucket
locals {
  all_files = fileset("${path.module}/files/${var.name}/", "**")
  # ignore any files that include `.terragrunt` in their filename
  relevant_files = [ for file in local.all_files: file if length(regexall("\\.terragrunt", file)) == 0 ]
}

output "Files_Copied_to_S3_by_this_Module" {
  value = local.relevant_files
}

resource "aws_s3_bucket_object" "populate" {
  for_each = toset(local.relevant_files)

  bucket = aws_s3_bucket.bucket.bucket
  key    = each.value
  source = "${path.module}/files/${var.name}/${each.value}"
  # etag makes the file update when it changes; see https://stackoverflow.com/questions/56107258/terraform-upload-file-to-s3-on-every-apply
  # But this does not work with kms encryption... 
  # TODO: When Source hash is merged, use that: https://github.com/hashicorp/terraform-provider-aws/pull/11522
  # Until then, leave it disabled.
  #etag   = filemd5("${path.module}/files/${var.name}/${each.value}")
}
