locals {
  # For reverse dns:
  # 0) Only take the first address
  first_address = var.ip_addresses[0]

  # 1) Split the ip addresses into 4 octets
  octets = regex("^(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+)$", local.first_address)

  # 2) Reverse them, but only if the first octet is 10 (maybe handle 192.168 and 172.16 later), and if enabled
  # NOTE: This used to ignore any that don't start with 10, but that causes headaches because:
  # > The "for_each" value depends on resource attributes that cannot be determined
  # > until apply, so Terraform cannot predict how many instances will be created.
  # > To work around this, use the -target argument to first apply only the
  # > resources that the for_each depends on.
  # So, we create the reverse no matter what, which means you should pass in 'reverse_disabled' if you're not
  # assignign out of the 10. network.
  reverse_address = join(".", reverse(slice(local.octets, 1, 4)))
}

resource "aws_route53_record" "dns" {
  count = var.enabled ? 1 : 0

  name = var.name
  type = "A"
  ttl  = 300
  zone_id = var.dns_info["private"]["zone_id"]
  records = var.ip_addresses
  provider = aws.c2
}

resource "aws_route53_record" "reverse_dns" {
  count = var.enabled && var.reverse_enabled ? 1 : 0

  name = local.reverse_address
  type = "PTR"
  ttl  = 300
  zone_id = var.dns_info["reverse"]["zone_id"]
  records = [ "${var.name}.${var.dns_info["private"]["zone"]}" ]
  provider = aws.c2
}
