#
# This machine exists for the end-user to ssh into and access
# internal-only ingresses.
#

output "user_machine_ssh_command" {
  description = "Command to launch an ssh shell on the user machine."
  value       = "gcloud compute ssh --zone '${var.zone}' --project '${google_project.project.project_id}' '${google_compute_instance.user_machine.name}'"
}

resource "google_service_account" "user_machine" {
  project      = google_project.project.project_id
  account_id   = "user-machine"
  display_name = "Custom SA for User Machine VM Instance"
}

resource "google_compute_instance" "user_machine" {
  project      = google_project.project.project_id
  name         = "user-machine"
  machine_type = "g1-small"
  zone         = var.zone
  tags         = ["allow-iap-ssh", "allow-python-http"]

  boot_disk {
    initialize_params {
      image = "debian-cloud/debian-12"
    }
  }

  network_interface {
    network    = google_compute_network.default.id
    subnetwork = google_compute_subnetwork.default.id
    network_ip = google_compute_address.user_machine.address
  }

  service_account {
    email  = google_service_account.user_machine.email
    scopes = ["cloud-platform"]
  }

  metadata = var.ssh_key != null ? {
    ssh-keys = var.ssh_key
  } : {}

  depends_on = [google_project_service.service["compute"], google_project_service.service["logging"]]
}

resource "google_compute_firewall" "allow_iap_ssh" {
  project   = google_project.project.project_id
  name      = "allow-iap-ssh"
  network   = google_compute_network.default.id
  direction = "INGRESS"
  allow {
    protocol = "tcp"
    ports    = ["22"]
  }
  source_ranges = ["35.235.240.0/20"]
  target_tags   = ["allow-iap-ssh"]
}

resource "google_compute_address" "user_machine" {
  project      = google_project.project.project_id
  name         = "user-machine"
  region       = var.region
  address_type = "INTERNAL"
  subnetwork   = google_compute_subnetwork.default.id
}

resource "google_dns_record_set" "user_machine" {
  project = google_project.project.project_id
  name    = "usermachine.${google_dns_managed_zone.zone.dns_name}"
  type    = "A"
  ttl     = 300

  managed_zone = google_dns_managed_zone.zone.name

  rrdatas = [google_compute_instance.user_machine.network_interface[0].network_ip]
}

resource "google_compute_firewall" "allow_python_http" {
  # This is for demoing SNAT, not needed for production.
  project   = google_project.project.project_id
  name      = "allow-python-http"
  network   = google_compute_network.default.id
  direction = "INGRESS"
  allow {
    protocol = "tcp"
    ports    = ["8080"]
  }
  source_ranges = ["0.0.0.0/0"]
  target_tags   = ["allow-python-http"]
}