locals {
  google_required_services = toset([
    "cloudkms.googleapis.com",
    "cloudresourcemanager.googleapis.com",
    "iam.googleapis.com",
  ])

  google_existing_kms_key_ring_id = var.google_kms_key_ring_id != "" ? var.google_kms_key_ring_id : "projects/${var.google_project_id}/locations/${var.google_kms_key_ring_location}/keyRings/${var.google_kms_key_ring_name}"

  google_kms_key_ring_id = var.manage_google_kms_key_ring ? (
    google_kms_key_ring.openbao[0].id
  ) : local.google_existing_kms_key_ring_id
}

resource "google_project_service" "openbao" {
  for_each = var.manage_google ? local.google_required_services : toset([])

  project            = var.google_project_id
  service            = each.value
  disable_on_destroy = false
}

resource "google_kms_key_ring" "openbao" {
  count = var.manage_google && var.manage_google_kms_key_ring ? 1 : 0

  project  = var.google_project_id
  location = var.google_kms_key_ring_location
  name     = var.google_kms_key_ring_name

  depends_on = [google_project_service.openbao]
}

resource "google_kms_crypto_key" "openbao_seal" {
  count = var.manage_google && local.google_kms_key_ring_id != "" ? 1 : 0

  name     = var.google_openbao_seal_key_name
  key_ring = local.google_kms_key_ring_id
  purpose  = "ENCRYPT_DECRYPT"
  labels = merge(
    {
      project    = "burrow"
      component  = "openbao"
      managed_by = "opentofu"
      key_target = "seal"
    },
    var.tags,
  )

  version_template {
    algorithm        = "GOOGLE_SYMMETRIC_ENCRYPTION"
    protection_level = "HSM"
  }

  lifecycle {
    prevent_destroy = true
  }
}

resource "google_kms_crypto_key_iam_member" "openbao_seal" {
  for_each = var.manage_google && local.google_kms_key_ring_id != "" ? var.google_openbao_seal_members : toset([])

  crypto_key_id = google_kms_crypto_key.openbao_seal[0].id
  role          = "roles/cloudkms.cryptoKeyEncrypterDecrypter"
  member        = each.value
}
