data "aws_iam_policy_document" "this" {
  statement {
    sid = "AllowListingOfUserFolder"
    actions = [
      "s3:ListBucket"
    ]
    effect = "Allow"
    resources = [
      var.s3_bucket_arn
    ]
    condition {
      test     = "StringLike"
      values   = [var.target_path, "${var.target_path}/*"]
      variable = "s3:prefix"
    }
  }

  statement {
    sid = "HomeDirObjectAccess"
    actions = [
      "s3:PutObject",
      "s3:GetObject",
      "s3:DeleteObjectVersion",
      "s3:DeleteObject",
      "s3:GetObjectVersion",
      "s3:GetObjectACL",
      "s3:PutObjectACL",
    ]
    effect = "Allow"
    resources = [
      "${var.s3_bucket_arn}/${var.target_path}/*"
    ]
  }
}

resource "aws_iam_policy" "this" {
  name        = "${var.name_prefix}-${var.name}"
  path        = var.path
  description = "Full access to subfolder in a bucket"
  policy      = data.aws_iam_policy_document.this.json
}
