variable "wait_on" {
  type        = any
  description = "Resources to wait on"
  default     = true
}

variable "server_ip" {
  description = "Target server IP"
  type        = string
}

variable "ssh_private_key_path" {
  description = "Path to SSH private key"
  type        = string
  default     = "~/.ssh/id_rsa"
}

variable "name" {
  description = "Name of the network"
  type        = string
}

resource "null_resource" "deploy_network" {
  depends_on = [var.wait_on]
  triggers = {
    name            = var.name
    server_ip           = var.server_ip
    ssh_private_key_path = var.ssh_private_key_path
  }

  provisioner "remote-exec" {
    inline = compact(flatten([
      [
        
        # Create base quadlet file
        "cat > /tmp/${var.name}.network << 'EOF'",
        "[Network]",
        "Description=${var.name} network",
        "",
        "[Install]",
        "WantedBy=default.target",
        "EOF",

        "test -d ~/.config/containers/systemd || mkdir -p ~/.config/containers/systemd",
        "cp /tmp/${var.name}.network ~/.config/containers/systemd/${var.name}.network",
        "systemctl --user daemon-reload",
      ]
    ]))


    connection {
      type        = "ssh"
      host        = var.server_ip
      user        = "fourlights"
      agent       = true
      agent_identity  = var.ssh_private_key_path
    }
  }

  provisioner "remote-exec" {
    when = destroy
    inline = [
      # Remove the .container file
      "rm -f ~/.config/containers/systemd/${self.triggers.name}.network",

      # Reload systemd to remove the generated service
      "systemctl --user daemon-reload",

      # Force remove any lingering containers
      "podman network rm -f ${self.triggers.name} || true"
    ]
    connection {
      type        = "ssh"
      host        = self.triggers.server_ip
      user        = "fourlights"
      agent       = true
      agent_identity  = self.triggers.ssh_private_key_path
    }

  }
}

output "name" {
  value = var.name
}

output "service_status" {
  value = "${var.name} deployed"
}

output "installed" {
  value = true
  depends_on = [null_resource.deploy_network]
}