locals {
  control_planes = sort([
    for name, node in var.nodes : name
    if node.role == "control-plane"
  ])

  workers = sort([
    for name, node in var.nodes : name
    if node.role == "worker"
  ])

  ssh_managed_nodes = sort([
    for name, node in var.nodes : name
    if node.managed
  ])

  ssh_node_hosts = {
    for name, node in var.nodes : name => node.ip
    if node.managed
  }

  ssh_node_users = {
    for name, node in var.nodes : name => node.ssh_user
    if node.managed && try(node.ssh_user, null) != null && node.ssh_user != var.default_ssh_user
  }

  required_node_labels = {
    for name, node in var.nodes : name => node.labels
    if length(node.labels) > 0
  }

  ignore_unavailable_nodes = sort([
    for name, node in var.nodes : name
    if node.ignore_unavailable
  ])

  ananke_inventory = {
    ssh_user          = var.default_ssh_user
    ssh_port          = var.default_ssh_port
    ssh_config_file   = var.default_ssh_config_file
    ssh_identity_file = var.default_ssh_identity_file
    ssh_node_hosts    = local.ssh_node_hosts
    ssh_node_users    = local.ssh_node_users
    ssh_managed_nodes = local.ssh_managed_nodes
    control_planes    = local.control_planes
    workers           = local.workers
    startup = {
      required_node_labels_mode = "validate"
      required_node_labels      = local.required_node_labels
      ignore_unavailable_nodes  = local.ignore_unavailable_nodes
    }
  }
}

resource "kubernetes_labels" "node" {
  for_each = local.required_node_labels

  api_version   = "v1"
  kind          = "Node"
  field_manager = var.label_field_manager
  force         = var.force_node_label_conflicts

  metadata {
    name = each.key
  }

  labels = each.value
}

resource "local_file" "ananke_inventory_fragment" {
  filename        = var.ananke_inventory_fragment_path
  file_permission = "0640"
  content         = "# Generated by Terraform. Do not add secrets here.\n${yamlencode(local.ananke_inventory)}"
}
