locals {
  kms_users = concat( 
          [
            "arn:${var.aws_partition}:iam::${var.aws_account_id}:user/MDRAdmin",
            "arn:${var.aws_partition}:iam::${var.aws_account_id}:role/user/mdr_terraformer",
          ],
          local.accounts
        )
}

resource "aws_kms_key" "bucketkey" {
  count                   = var.encryption == "SSE-KMS" ? 1 : 0
  description             = "S3 KMS for ${var.name}."
  deletion_window_in_days = 30
  enable_key_rotation     = true
  policy                  = data.aws_iam_policy_document.kms_key_policy.json
  tags                    = merge(var.standard_tags, var.tags)
}

resource "aws_kms_alias" "bucketkey" {
  count         = var.encryption == "SSE-KMS" ? 1 : 0
  name          = "alias/${var.name}"
  target_key_id = aws_kms_key.bucketkey[0].key_id
}

data "aws_iam_policy_document" "kms_key_policy" {
  policy_id = var.name
  statement {
    sid    = "Enable IAM User Permissions"
    effect = "Allow"
    principals {
      type        = "AWS"
      identifiers = [
        "arn:${var.aws_partition}:iam::${var.aws_account_id}:root",
        "arn:${var.aws_partition}:iam::${var.aws_account_id}:user/MDRAdmin",
      ]
    }
    actions   = ["kms:*"]
    resources = ["*"]
  }

  statement {
    sid    = "Allow access for Engineers"
    effect = "Allow"
    principals {
      type = "AWS"
      identifiers = [
        "arn:${var.aws_partition}:iam::${var.aws_account_id}:user/MDRAdmin",
        "arn:${var.aws_partition}:iam::${var.aws_account_id}:role/user/mdr_terraformer",
      ]
    }

    actions = [
      "kms:Create*",
      "kms:Describe*",
      "kms:Enable*",
      "kms:List*",
      "kms:Put*",
      "kms:Update*",
      "kms:Revoke*",
      "kms:Disable*",
      "kms:Get*",
      "kms:Delete*",
      "kms:TagResource",
      "kms:UntagResource",
      "kms:ScheduleKeyDeletion",
      "kms:CancelKeyDeletion"
    ]
    resources = ["*"]
  }

  statement {
    sid    = "Allow use of the key to encrypt and decrypt"
    effect = "Allow"
    principals {
      type = "AWS"
      identifiers = local.kms_users
    }
    actions = [
      "kms:Encrypt",
      "kms:Decrypt",
      "kms:ReEncrypt*",
      "kms:GenerateDataKey*",
      "kms:DescribeKey"
    ]
    resources = ["*"]
  }

  statement {
    sid    = "Allow attachment of persistent resources"
    effect = "Allow"
    principals {
      type = "AWS"
      identifiers = [
        "arn:${var.aws_partition}:iam::${var.aws_account_id}:user/MDRAdmin",
        "arn:${var.aws_partition}:iam::${var.aws_account_id}:role/user/mdr_terraformer",
      ]
    }
    actions = [
      "kms:CreateGrant",
      "kms:ListGrants",
      "kms:RevokeGrant"
    ]
    resources = ["*"]
    condition {
      test     = "Bool"
      variable = "kms:GrantIsForAWSResource"
      values   = ["true"]
    }
  }

  # TODO: Do we need to grant read access to other accounts?
}
