provider "hcloud" {
  token = var.hcloud_token
}

resource "tls_private_key" "root" {
  algorithm = "RSA"
  rsa_bits  = 4096
}

resource "hcloud_ssh_key" "this" {
  name       = var.ssh_key_name
  public_key = one(tls_private_key.root[*].public_key_openssh)
}

resource "local_sensitive_file" "ssh_private_key" {
  filename             = "${var.files_dir}/id_rsa"
  file_permission      = "0600"
  directory_permission = "0755"
  content              = one(tls_private_key.root[*].private_key_pem)
}

resource "hcloud_server" "under_test" {
  name   = var.hcloud_server_under_test_name
  labels = { "os" = "coreos" }

  server_type = var.hcloud_server_under_test_type
  datacenter  = var.hcloud_server_datacenter

  # Image is ignored, as we boot into rescue mode, but is a required field
  image    = "fedora-36"
  rescue   = "linux64"
  ssh_keys = concat(hcloud_ssh_key.this[*].name, var.ssh_extra_key_names)


  connection {
    host        = hcloud_server.under_test.ipv4_address
    timeout     = "5m"
    private_key = file(local_sensitive_file.ssh_private_key.filename)
    # Root is the available user in rescue mode
    user = "root"
  }

  provisioner "local-exec" {
    command = "butane --pretty --strict -d . configure.bu > ${var.files_dir}/configure.ign"
  }


  # Copy Ignition config to server
  provisioner "file" {
    content     = file("${var.files_dir}/configure.ign")
    destination = "/root/setup.ign"
  }

  # Install Fedora CoreOS in rescue mode
  provisioner "remote-exec" {
    inline = [
      "set -x",
      "set -e",
      "wget https://s3.tobiasmanske.de/public/tobias/coreos-installer-hetzner/main/coreos-installer -O /usr/local/bin/coreos-installer",
      "chmod 755 /usr/local/bin/coreos-installer",
      "coreos-installer install /dev/sda -i /root/setup.ign",
      "shutdown -r now"
    ]
  }
}