# Sadly, this would be far easier if we could use for_each in a module. We can't, so we're cutting and pasting
# code from submodules/dns/private_A_record
locals {
  # For reverse dns:
  # 1) Split the ip addresses into 4 octets
  private_octets = { for name, address in var.legacy_private_dns: name => regex("^(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+)$", address) }
  # 2) Reverse them, but only if the first octet is 10 (maybe handle 192.168 and 172.16 later), and if enabled
  private_reverse_addresses = { for name, octets in local.private_octets: name => join(".", reverse(slice(octets, 1, 4))) if octets[0] == "10" }
}

# Private
resource "aws_route53_record" "private" {
  for_each = var.legacy_private_dns

  name = each.key
  type = "A"
  ttl  = 300
  zone_id = var.dns_info["private"]["zone_id"]
  records = [ each.value ]
  provider = aws.c2
}
resource "aws_route53_record" "private_cname" {
  for_each = var.legacy_private_cname_dns

  name = each.key
  type = "CNAME"
  ttl  = 300
  zone_id = var.dns_info["private"]["zone_id"]
  records = [ each.value ]
  provider = aws.c2
}

# Reverse
resource "aws_route53_record" "reverse_dns" {
  for_each = local.private_reverse_addresses
  name = each.value
  type = "PTR"
  ttl  = 300
  zone_id = var.dns_info["reverse"]["zone_id"]
  records = [ "${each.key}.${var.dns_info["private"]["zone"]}." ]
  provider = aws.c2
}

# Public
resource "aws_route53_record" "public" {
  for_each = var.legacy_public_dns

  name = each.key
  type = "A"
  ttl  = 300
  zone_id = var.dns_info["public"]["zone_id"]
  records = [ each.value ]
  provider = aws.mdr-common-services-commercial
}

# Public cname
resource "aws_route53_record" "public_cname" {
  for_each = var.legacy_public_cname_dns

  name = each.key
  type = "CNAME"
  ttl  = 300
  zone_id = var.dns_info["public"]["zone_id"]
  records = [ each.value ]
  provider = aws.mdr-common-services-commercial
}
