resource "aws_kms_key" "key" {
  description = "Key for AMI Backups"
  enable_key_rotation = true
  policy = data.aws_iam_policy_document.kms_policy.json
  tags = merge(
    var.standard_tags,
    { "Name" = "ami_backup_key" },
    var.tags
  )
}

resource "aws_kms_alias" "alias" {
  name          = "alias/ami_backup_key"
  target_key_id = aws_kms_key.key.key_id
}

data "aws_iam_policy_document" "kms_policy" {
  policy_id = "backup-ami-key-policy"

  statement {
    sid = "Enable IAM User Permissions"
    effect = "Allow"
    principals {
      type = "AWS"
      identifiers = [ 
        # The 'root' account is the entire account, we don't want that
        #"arn:${var.aws_partition}:iam::${var.aws_account_id}:root" 
        "arn:${var.aws_partition}:iam::${var.aws_account_id}:user/MDRAdmin", # MDRAdmin as a break glass
        "arn:${var.aws_partition}:iam::${var.aws_account_id}:role/user/mdr_terraformer" # Terraformer always gets full access
      ]
    }
    actions = [ "kms:*" ]
    resources = [ "*" ]
  }

  statement {
    sid = "Allow access for Key Administrators"
    effect = "Allow"
    principals {
      type = "AWS"
      identifiers = [ "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"
    effect = "Allow"
    principals {
      type = "AWS"
      identifiers = [ 
        "arn:${var.aws_partition}:iam::${var.aws_account_id}:role/user/mdr_terraformer",
        "arn:${var.aws_partition}:iam::${var.aws_account_id}:role/dlm-lifecycle-role"
      ]
    }
    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}:role/user/mdr_terraformer",
        "arn:${var.aws_partition}:iam::${var.aws_account_id}:role/dlm-lifecycle-role"
      ]
    }
    actions = [
      "kms:CreateGrant",
      "kms:ListGrants",
      "kms:RevokeGrant"
    ]
    resources = [ "*" ]
  }
}
