data "aws_caller_identity" "current" {}

data "aws_iam_user" "admins" {
  count     = length(var.admin_users)
  user_name = var.admin_users[count.index]
}

data "aws_iam_role" "admin_roles" {
  count = length(var.admin_roles)
  name  = var.admin_roles[count.index]
}

locals {
  root_arn                = "arn:aws:iam::${local.account_id}:root"
  admin_roles_ids         = formatlist("%s:*", data.aws_iam_role.admin_roles[*].unique_id)
  external_read_enabled   = length(var.external_read_arns) == 0 ? [] : ["Allow external read IAM roles"]
  external_upload_enabled = length(var.external_upload_arns) == 0 ? [] : ["Allow external upload IAM roles"]
  external_delete_enabled = length(var.external_delete_arns) == 0 ? [] : ["Allow external upload IAM roles"]
  account_id              = data.aws_caller_identity.current.account_id
  ses_account_id          = var.ses_account_id != "" ? [var.ses_account_id] : []
}

data "aws_iam_policy_document" "main" {
  version                 = "2012-10-17"
  source_policy_documents = var.encryption_in_transit ? [module.default_bucket_policy.document.json] : null
  #policy_id = "Resource policy for ${var.bucket}"

  statement {
    sid    = "Deny administrative operations"
    effect = "Deny"
    actions = sort([
      "s3:PutBucketNotification",
      "s3:PutBucketPublicAccessBlock",
      "s3:PutAnalyticsConfiguration",
      "s3:PutAccelerateConfiguration",
      "s3:PutMetricsConfiguration",
      "s3:PutReplicationConfiguration",
      "s3:PutBucketCORS",
      "s3:DeleteBucketPolicy",
      "s3:PutInventoryConfiguration",
      "s3:PutEncryptionConfiguration",
      "s3:DeleteBucketWebsite",
      "s3:PutBucketLogging",
      "s3:PutLifecycleConfiguration",
      "s3:PutBucketAcl",
      "s3:PutBucketPolicy",
      "s3:PutBucketObjectLockConfiguration",
      "s3:DeleteBucket"
    ])
    resources = sort([
      "${var.template_bucket_arn}/*",
      var.template_bucket_arn
    ])
    principals {
      type        = "AWS"
      identifiers = ["*"]
    }
    condition {
      test     = "StringNotLike"
      variable = "aws:UserId"
      values = sort(concat(
        data.aws_iam_user.admins[*].user_id,
        local.admin_roles_ids,
        [local.account_id]
      ))
    }
  }

  dynamic "statement" {
    for_each = var.denied_paths_for_roles
    content {
      effect    = "Deny"
      actions   = ["s3:*"]
      resources = sort(formatlist("${var.template_bucket_arn}/%s", statement.value.paths))
      principals {
        type        = "AWS"
        identifiers = sort(formatlist("arn:aws:iam::${local.account_id}:role/%s", statement.value.roles))
      }
    }
  }

  dynamic "statement" {
    for_each = var.denied_paths_for_external_roles
    content {
      effect    = "Deny"
      actions   = ["s3:*"]
      resources = sort(formatlist("${var.template_bucket_arn}/%s", statement.value.paths))
      principals {
        type        = "AWS"
        identifiers = sort(statement.value.role_arns)
      }
    }
  }

  dynamic "statement" {
    for_each = local.external_delete_enabled
    content {
      sid    = "Explicit allow for external delete"
      effect = "Allow"
      actions = [
        "s3:DeleteObject",
        "s3:DeleteObjectTagging",
        "s3:DeleteObjectVersion",
        "s3:DeleteObjectVersionTagging"
      ]
      resources = sort([
        "${var.template_bucket_arn}/*",
        var.template_bucket_arn
      ])
      principals {
        type        = "AWS"
        identifiers = sort(var.external_delete_arns)
      }
    }
  }

  dynamic "statement" {
    for_each = local.external_read_enabled
    content {
      sid    = "Explicit allow for external read"
      effect = "Allow"
      actions = [
        "s3:GetObject",
        "s3:ListBucket",
        "s3:GetObjectTagging",
        "s3:GetObjectVersion",
        "s3:GetObjectVersionTagging"
      ]
      resources = sort([
        "${var.template_bucket_arn}/*",
        var.template_bucket_arn
      ])
      principals {
        type        = "AWS"
        identifiers = sort(var.external_read_arns)
      }
    }
  }

  dynamic "statement" {
    for_each = local.external_upload_enabled
    content {
      sid    = "Explicit allow list uploads and put objects and version tagging"
      effect = "Allow"
      actions = [
        "s3:ListMultipartUploadParts",
        "s3:AbortMultipartUpload",
        "s3:ListBucketMultipartUploads",
        "s3:PutObjectVersionTagging",
        "s3:PutObjectTagging",
        "s3:PutObject",
        "s3:PutObjectAcl",
      ]
      resources = sort([
        "${var.template_bucket_arn}/*",
        var.template_bucket_arn
      ])
      principals {
        type        = "AWS"
        identifiers = sort(var.external_upload_arns)
      }
    }
  }

  # Permissions for custom roles on custom paths
  dynamic "statement" {
    for_each = var.custom_path_permissions
    content {
      sid    = "Custom permissions for ${statement.value.arn} path ${statement.value.path}"
      effect = "Allow"
      actions = sort(concat(statement.value.read ? [
        "s3:GetObject",
        "s3:ListBucket",
        "s3:GetObjectTagging",
        "s3:GetObjectVersion",
        "s3:GetObjectVersionTagging"
        ] : [],
        statement.value.write ? [
          "s3:ListMultipartUploadParts",
          "s3:AbortMultipartUpload",
          "s3:ListBucketMultipartUploads",
          "s3:PutObjectVersionTagging",
          "s3:PutObjectTagging",
          "s3:PutObject",
          "s3:PutObjectAcl",
        ] : [],
        statement.value.delete ? [
          "s3:DeleteObject",
          "s3:DeleteObjectTagging",
          "s3:DeleteObjectVersion",
          "s3:DeleteObjectVersionTagging"
        ] : []
      ))
      resources = sort([
        "${var.template_bucket_arn}/${statement.value.path}*",
        var.template_bucket_arn
      ])
      principals {
        type        = "AWS"
        identifiers = [statement.value.arn]
      }
    }
  }

  # SES
  dynamic "statement" {
    for_each = local.ses_account_id
    content {
      sid    = "Allow SES to write"
      effect = "Allow"
      actions = [
        "s3:PutObject",
      ]
      resources = [
        "${var.template_bucket_arn}/*"
      ]
      principals {
        type        = "Service"
        identifiers = ["ses.amazonaws.com"]
      }
      condition {
        test     = "StringEquals"
        values   = [statement.value]
        variable = "aws:Referer"
      }
    }
  }

  # Replication statements
  dynamic "statement" {
    for_each = length(var.replication_roles) > 0 ? ["Enabled"] : []
    content {
      sid    = "ReplicationPolicy1"
      effect = "Allow"
      actions = [
        "s3:ReplicateDelete",
        "s3:ReplicateObject",
        "s3:ObjectOwnerOverrideToBucketOwner",
      ]
      resources = ["${var.template_bucket_arn}/*"]
      principals {
        type        = "AWS"
        identifiers = var.replication_roles
      }
    }
  }

  dynamic "statement" {
    for_each = length(var.replication_roles) > 0 ? ["Enabled"] : []
    content {
      sid    = "ReplicationPolicy2"
      effect = "Allow"
      actions = [
        "s3:List*",
        "s3:GetBucketVersioning",
        "s3:PutBucketVersioning",
      ]
      resources = ["${var.template_bucket_arn}"]
      principals {
        type        = "AWS"
        identifiers = var.replication_roles
      }
    }
  }
}

module "default_bucket_policy" {
  source              = "../default_policy_template"
  template_bucket_arn = var.template_bucket_arn
}
