# --- Cloud-Init für Server ---
terraform {
  required_providers {
    libvirt = {
      source  = "dmacvicar/libvirt"
      version = "0.8.3"
    }
  }
}

data "cloudinit_config" "server_init" {
  gzip          = false
  base64_encode = false

  part {
    content_type = "text/cloud-config"
    content = templatefile("${path.module}/cloud_init.cfg.yml", {
      user = var.vm_user
      ssh_authorized_keys = [chomp(file(pathexpand(var.ssh_public_key_path)))]
      hostname = var.server_hostname
    })
  }
}

resource "libvirt_cloudinit_disk" "server_iso" {
  name      = "${var.server_hostname}-init.iso"
  user_data = data.cloudinit_config.server_init.rendered
  pool      = var.libvirt_pool
}

# --- Cloud-Init für Agenten ---
data "cloudinit_config" "agent_init" {
  count         = var.agent_count
  gzip          = false
  base64_encode = false

  part {
    content_type = "text/cloud-config"
    content = templatefile("${path.module}/cloud_init.cfg.yml", {
      user = var.vm_user
      ssh_authorized_keys = [chomp(file(pathexpand(var.ssh_public_key_path)))]
      hostname = "${var.agent_hostname_prefix}-${count.index + 1}"
    })
  }
}

resource "libvirt_cloudinit_disk" "agent_iso" {
  count     = var.agent_count
  name      = "${var.agent_hostname_prefix}-${count.index + 1}-init.iso"
  user_data = data.cloudinit_config.agent_init[count.index].rendered
  pool      = var.libvirt_pool
}

# --- K3s Server Node ---
resource "libvirt_domain" "server" {
  name   = var.server_hostname
  memory = var.server_memory
  vcpu   = var.server_vcpu

  cloudinit = libvirt_cloudinit_disk.server_iso.id

  network_interface {
    network_name = var.libvirt_network_name
    addresses    = [var.server_ip]
    wait_for_lease = true
  }

  disk {
    volume_id = libvirt_volume.server_disk.id
  }

  console {
    type        = "pty"
    target_port = "0"
    target_type = "serial"
  }
  graphics {
    type        = "spice"
    listen_type = "address"
    autoport    = true
  }
}

# --- K3s Agent Nodes ---
resource "libvirt_domain" "agent" {
  count  = var.agent_count
  name   = "${var.agent_hostname_prefix}-${count.index + 1}"
  memory = var.agent_memory
  vcpu   = var.agent_vcpu

  cloudinit = libvirt_cloudinit_disk.agent_iso[count.index].id

  network_interface {
    network_name = var.libvirt_network_name
    addresses    = [var.agent_ips[count.index]]
    wait_for_lease = true
  }

  disk {
    volume_id = libvirt_volume.agent_disk[count.index].id
  }

  console {
    type        = "pty"
    target_port = "0"
    target_type = "serial"
  }
  graphics {
    type        = "spice"
    listen_type = "address"
    autoport    = true
  }
}


