$SiteRoot = "\\zusscgrcprodwebhelp.file.core.windows.net\webhelp\prod"
$ANCHOR_TAG_PATTERN = "<\s*a\s*[^>]*?href\s*=\s*[`"']*([^`"'>]+)[^>]*?>"
$OutFilePath = "$PSScriptRoot\Invalid-Links.txt"

#region Helper Functions
function GetMatches([string] $content, [string] $regex)
{
    $returnMatches = new-object System.Collections.ArrayList
    $resultingMatches = [Regex]::Matches($content, $regex, "IgnoreCase")
    foreach($match in $resultingMatches)
    {
        $cleanedMatch = $match.Groups[1].Value.Trim()
        [void] $returnMatches.Add($cleanedMatch)
    }
    $returnMatches
}

if ([System.IO.File]::Exists($OutFilePath))
{
    [System.IO.File]::Delete($OutFilePath)
}

function Write-Line
{
    Param
    (
        [string] $line
    )

    #Write-Host $Line
    $Line | Out-File $OutFilePath -Append
}

#endregion

#region Execution Hook Functions

function ShouldIncludeLink($link)
{
    # Purpose: Determine if the "href" value is something we should care about...

    if ($link.startsWith("#"))
    {
        return $false
    }
    else
    {
        return $true
    }
}

function GetFullPath($info, $tag)
{
    # Purpose: Gets the full path of whatever's in the "href" value for each tag.

    # TODO: Add more cases as needed...

    $Root = $Info.Directory

    if ($tag.startsWith("/"))
    {
        $Root = $SiteRoot
    }

    $filePath = $(Join-Path -Path $Root -ChildPath $tag.replace('/', '\'))

    return [System.IO.Path]::GetFullPath($filePath)
}

function CleanTag($tag)
{
    # Purpose: Cleans the "href" attribute value for each "a" tag

    # TODO: Add more cases as needed...

    # CASE: foobar.html#r7457237 --> foobar.html

    $parts = $tag.split('#')

    if ($parts.count -gt 1)
    {
        $tag = $parts[0].trim()
    }

    # CASE: Foo%20Bar.html --> Foo Bar.html

    $tag = $tag.replace("%20", " ")

    return $tag
}

#endregion

# --------------------------------------------------
# Read all .html files and parse anchor tag hrefs
# --------------------------------------------------

foreach ($file in $([System.IO.Directory]::EnumerateFiles($SiteRoot, "*.html", "AllDirectories")))
{
    $info = New-Object System.IO.FileInfo $file

    $text = $(Get-Content -Raw $file)
    $anchorTags = @(GetMatches $text $ANCHOR_TAG_PATTERN)
    $links = [System.Collections.ArrayList]@()

    foreach ($tag in $anchorTags | Where-Object { $(ShouldIncludeLink -link $_) })
    {
        $cleanTag = CleanTag -tag $tag
        $filePath = GetFullPath -info $info -tag $cleanTag

        if (-not [System.IO.File]::Exists($filePath))
        {
            $links.Add($cleanTag) | Out-Null
        }
    }

    if ($links.count -gt 0)
    {
        $relativePath = [System.IO.Path]::GetRelativePath($SiteRoot, $file)

        Write-Line $relativePath
        Write-Line ""
        Write-Line $file
        foreach ($link in $links)
        {
            Write-Line "- $link"
        }

        Write-Line ""
    }
}
