# Creates a GCE VM (+ the minimal networking it needs) for the thermograph-host
# module to then provision over SSH — this module contributes NOTHING to
# provisioning logic (no Docker install, no compose, no secrets rendering); it
# only stands the box up and hands its IP back. See ../../main.tf's module.gcp_vm
# / module.host composition. Scaffold only: nothing here is applied until a
# caller populates var.gcp_hosts (root variables.tf) with a real entry.

# A dedicated VPC rather than the project's "default" network, so this doesn't
# depend on (or clutter) whatever else may already exist in the project.
resource "google_compute_network" "this" {
  project                 = var.project
  name                    = "thermograph-${var.name}"
  auto_create_subnetworks = false
}

resource "google_compute_subnetwork" "this" {
  project       = var.project
  name          = "thermograph-${var.name}"
  network       = google_compute_network.this.id
  region        = join("-", slice(split("-", var.zone), 0, 2))
  ip_cidr_range = "10.20.0.0/24"
}

# 22/80/443 only -- matches the SSH-managed hosts' own ufw rules (thermograph-host
# module's setup step). The app port itself is opened by that same module's ufw
# step when the host has no domain, same as any other host it provisions.
resource "google_compute_firewall" "allow_ingress" {
  project       = var.project
  name          = "thermograph-${var.name}-allow-ingress"
  network       = google_compute_network.this.id
  source_ranges = ["0.0.0.0/0"]

  allow {
    protocol = "tcp"
    ports    = ["22", "80", "443"]
  }
}

resource "google_compute_instance" "this" {
  project      = var.project
  name         = "thermograph-${var.name}"
  zone         = var.zone
  machine_type = var.machine_type

  boot_disk {
    initialize_params {
      # Debian: matches the apt-based setup script thermograph-host's
      # provisioner runs (Docker's get.docker.com installer, ufw, Caddy's apt repo).
      image = "debian-cloud/debian-12"
      size  = 30
    }
  }

  network_interface {
    subnetwork = google_compute_subnetwork.this.id
    access_config {} # ephemeral public IP
  }

  metadata = {
    ssh-keys = "${var.ssh_user}:${file(pathexpand(var.ssh_public_key_path))}"
  }
}

# A brief pause before the caller's thermograph-host module opens an SSH
# connection: a fresh GCE instance's sshd is not always immediately reachable
# the instant the API reports the instance RUNNING (cloud-init/sshd startup is a
# known race here, distinct from the null_resource provisioner's own timeout).
resource "time_sleep" "wait_for_ssh" {
  create_duration = "30s"
  depends_on      = [google_compute_instance.this]
}

output "external_ip" {
  description = "Public IP of the created instance, once it (and a short settle delay) exist."
  value       = google_compute_instance.this.network_interface[0].access_config[0].nat_ip
  depends_on  = [time_sleep.wait_for_ssh]
}
