terraform {
  required_providers {
    hcloud = {
      source  = "hetznercloud/hcloud"
      version = "~> 1.45"
    }
  }
}

# One overseas reference probe point (doc/04 §4.2). It runs the probe script and
# reports TCP/TLS/real-handshake reachability of data-plane nodes back to the
# control plane, used to distinguish "blocked" from "machine down".
resource "hcloud_server" "probe" {
  name        = "pangolin-probe-${var.name}"
  server_type = var.server_type
  image       = var.image
  location    = var.location
  ssh_keys    = var.ssh_key_ids

  labels = {
    role    = "probe"
    project = "pangolin"
    scope   = "overseas-reference"
  }

  # Probe bootstrap: pin + install the probe agent out-of-band. Kept minimal;
  # probes hold NO data-plane secrets and NO user data.
  user_data = <<-EOT
    #cloud-config
    package_update: true
    runcmd:
      - sed -i 's/^#\?PermitRootLogin.*/PermitRootLogin prohibit-password/' /etc/ssh/sshd_config
      - sed -i 's/^#\?PasswordAuthentication.*/PasswordAuthentication no/' /etc/ssh/sshd_config
      - systemctl restart sshd || true
  EOT

  lifecycle {
    create_before_destroy = true
  }
}

# Firewall: probes only need outbound; lock inbound to SSH from management.
resource "hcloud_firewall" "probe" {
  name = "pangolin-probe-${var.name}"

  rule {
    direction  = "in"
    protocol   = "tcp"
    port       = "22"
    source_ips = length(var.ssh_allowlist_cidrs) > 0 ? var.ssh_allowlist_cidrs : ["0.0.0.0/0", "::/0"]
  }
}

resource "hcloud_firewall_attachment" "probe" {
  firewall_id = hcloud_firewall.probe.id
  server_ids  = [hcloud_server.probe.id]
}
