resource "aws_kms_key" "tfstate" {
  description             = "tfstate bucket default S3 SSE-KMS"
  deletion_window_in_days = 30
  enable_key_rotation     = true
  policy                  = data.aws_iam_policy_document.kms_key_policy_tfstate.json

  depends_on = [ var.module_depends_on ]
}

resource "aws_kms_alias" "tfstate" {
  name          = "alias/tfstate"
  target_key_id = aws_kms_key.tfstate.key_id

  depends_on = [ var.module_depends_on ]
}


data "aws_iam_policy_document" "kms_key_policy_tfstate" {

  policy_id = "key-consolepolicy-3"
  statement {
    sid    = "Enable IAM User Permissions"
    effect = "Allow"
    principals {
      type        = "AWS"
      identifiers = ["arn:${local.aws_partition}:iam::${local.aws_account}:root"]
    }
    actions   = ["kms:*"]
    resources = ["*"]
  }

  statement {
    sid    = "Allow access for Key Administrators"
    effect = "Allow"
    principals {
      type = "AWS"
      identifiers = [
        # FIXME:  I'm trying to decide if these should be hard-coded or
        # parameters, or some mix/match of each.  
        "arn:${local.aws_partition}:iam::${local.aws_account}:user/MDRAdmin",
        #"arn:${local.aws_partition}:iam::${local.aws_account}:role/user/mdr_engineer",
        #"arn:${local.aws_partition}:iam::${local.aws_account}:role/user/mdr_iam_admin"
      ]
    }

    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"
    effect = "Allow"
    principals {
      type = "AWS"
      identifiers = [
        "arn:${local.aws_partition}:iam::${local.aws_account}:user/MDRAdmin",
        #"arn:${local.aws_partition}:iam::${local.aws_account}:role/user/mdr_engineer",
        #"arn:${local.aws_partition}:iam::${local.aws_account}:role/user/mdr_iam_admin"
      ]
    }
    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:${local.aws_partition}:iam::${local.aws_account}:user/MDRAdmin",
        #"arn:${local.aws_partition}:iam::${local.aws_account}:role/user/mdr_engineer",
        #"arn:${local.aws_partition}:iam::${local.aws_account}:role/user/mdr_iam_admin"
      ]
    }
    actions = [
      "kms:CreateGrant",
      "kms:ListGrants",
      "kms:RevokeGrant"
    ]
    resources = ["*"]
    condition {
      test     = "Bool"
      variable = "kms:GrantIsForAWSResource"
      values   = ["true"]
    }
  }
}
