variable "hdns_token" {}
variable "zone" { default = "fourlights.dev" }
variable "ipv4_address" {}
variable "ipv6_address" {}

variable "root" {}

terraform {
  required_providers {
    hetznerdns = {
      source  = "timohirt/hetznerdns"
      version = "2.2.0"
    }
  }
}

provider "hetznerdns" {
  apitoken = var.hdns_token
}

resource "hetznerdns_zone" "zone" {
  name = var.zone
  ttl  = 300
}

resource "hetznerdns_record" "server_root_ipv4" {
  zone_id = hetznerdns_zone.zone.id
  name    = var.root == null || var.root == "" ? "@" : var.root
  value   = var.ipv4_address
  type    = "A"
}

resource "hetznerdns_record" "server_root_ipv6" {
  zone_id = hetznerdns_zone.zone.id
  name    = var.root == null || var.root == "" ? "@" : var.root
  value   = var.ipv6_address
  type    = "AAAA"
}

resource "hetznerdns_record" "server_wildcard" {
  zone_id = hetznerdns_zone.zone.id
  name    = var.root == null || var.root == "" ? "*" : "*.${var.root}"
  value   = var.root
  type    = "CNAME"
}

locals {
  root_suffix = var.root == null || var.root == "" ? "" : "."
}

output "server_domain" {
  value = "${var.root}${local.root_suffix}${var.zone}"
}