terraform {
  required_providers {
    null = {
      source  = "hashicorp/null"
      version = "3.2.1"
    }
    template = {
      source  = "hashicorp/template"
      version = "2.2.0"
    }
  }
}

provider "template" {}

variable "nodes" {
  description = "Map of nodes with host, password, bind interface, and host volumes"
  type = map(object({
    host              = string
    password          = string
    bind_interface    = string
    bootstrap         = optional(bool, false)  # Optional field for bootstrap nodes
    cpu_total_compute = optional(number, null) # Optional field for CPU total compute
    node_class        = optional(string, null) # Optional Nomad node_class for scheduling constraints
    host_volumes      = list(string)
  }))
}

locals {
  config_files = { for k, v in var.nodes :
    k => templatefile("${path.module}/configuration.nix", {
      hostname          = v.host
      bind_interface    = v.bind_interface
      bootstrap         = v.bootstrap
      cpu_total_compute = v.cpu_total_compute
      node_class        = v.node_class
      host_volumes      = v.host_volumes
    })
  }
}

resource "null_resource" "deploy_nixos" {
  for_each = var.nodes

  connection {
    type     = "ssh"
    host     = "${each.value.host}.lan"
    user     = "root"
    password = each.value.password
  }

  provisioner "file" {
    content     = local.config_files[each.key]
    destination = "/tmp/configuration.nix"
  }

  provisioner "remote-exec" {
    inline = [
      "mv /tmp/configuration.nix /etc/nixos/configuration.nix",
      "nixos-rebuild switch --use-remote-sudo"
    ]
  }

  triggers = {
    configuration_content = local.config_files[each.key]
  }
}
