param(
  [string] $Domain = "k2aley.com",
  [string] $ExpectedIp = "70.160.138.181"
)

$ErrorActionPreference = "Stop"

$checks = @(
  @{ Name = $Domain; Type = "A"; Server = "ns1.bluehost.com" },
  @{ Name = $Domain; Type = "A"; Server = "ns2.bluehost.com" },
  @{ Name = "www.$Domain"; Type = "CNAME"; Server = "ns1.bluehost.com" },
  @{ Name = "www.$Domain"; Type = "A"; Server = "ns1.bluehost.com" },
  @{ Name = "www.$Domain"; Type = "A"; Server = "ns2.bluehost.com" },
  @{ Name = $Domain; Type = "A"; Server = "1.1.1.1" },
  @{ Name = $Domain; Type = "A"; Server = "8.8.8.8" },
  @{ Name = "www.$Domain"; Type = "A"; Server = "1.1.1.1" },
  @{ Name = "www.$Domain"; Type = "A"; Server = "8.8.8.8" }
)

$rows = foreach ($check in $checks) {
  try {
    $answers = Resolve-DnsName -Server $check.Server -Name $check.Name -Type $check.Type -ErrorAction Stop |
      Where-Object { $_.Type -in @("A", "CNAME") }

    if (-not $answers) {
      [pscustomobject]@{
        Server = $check.Server
        Name = $check.Name
        QueryType = $check.Type
        AnswerType = ""
        IPAddress = ""
        NameHost = ""
        Status = "MISSING"
      }
      continue
    }

    foreach ($answer in $answers) {
      [pscustomobject]@{
        Server = $check.Server
        Name = $check.Name
        QueryType = $check.Type
        AnswerType = $answer.Type
        IPAddress = $answer.IPAddress
        NameHost = $answer.NameHost
        Status = if ($answer.IPAddress -eq $ExpectedIp -or $answer.NameHost -eq $Domain) { "PASS" } else { "CHECK" }
      }
    }
  } catch {
    [pscustomobject]@{
      Server = $check.Server
      Name = $check.Name
      QueryType = $check.Type
      AnswerType = ""
      IPAddress = ""
      NameHost = ""
      Status = "MISSING"
    }
  }
}

$rows | Format-Table -AutoSize

$requiredChecks = $checks | Where-Object {
  $_.Type -eq "A"
}

$failedChecks = foreach ($check in $requiredChecks) {
  $matchingRows = $rows | Where-Object {
    $_.Server -eq $check.Server -and
    $_.Name -eq $check.Name -and
    $_.QueryType -eq $check.Type
  }

  $hasExpectedAnswer = $matchingRows | Where-Object {
    ($_.AnswerType -eq "A" -and $_.IPAddress -eq $ExpectedIp) -or
    ($_.Name -eq "www.$Domain" -and $_.AnswerType -eq "CNAME" -and $_.NameHost -eq $Domain)
  }

  if (-not $hasExpectedAnswer) {
    [pscustomobject]$check
  }
}

if ($failedChecks.Count -eq 0) {
  Write-Host "DNS PASS: $Domain and www.$Domain resolve toward $ExpectedIp" -ForegroundColor Green
  exit 0
}

Write-Host "DNS NOT READY OR STILL PROPAGATING: add A @ -> $ExpectedIp and A www -> $ExpectedIp, then rerun this script until every required A lookup is PASS. CNAME www -> $Domain is also valid only when no other www records exist." -ForegroundColor Yellow
exit 1
