param (
    [parameter(Mandatory=$false)]
    [Alias('i')]
    [switch]
    $InteractiveMode = $false
)

$host.ui.RawUI.WindowTitle = "VC Redist Check"

$FoundMessage = 'Found! Detected Version {0}'

# Check the major version.
$VC_Runtimes_x86_Path = 'HKLM:\SOFTWARE\Wow6432Node\Microsoft\VisualStudio\14.0\VC\Runtimes\x86';

Write-Host
Write-Host "Checking version number in $VC_Runtimes_x86_Path..."

$Major = 0
try {
    $Major = Get-ItemPropertyValue -Path $VC_Runtimes_x86_Path -Name Major
}
catch {
}

if ($Major -ge 14) {
    try {
        $Minor = Get-ItemPropertyValue -Path $VC_Runtimes_x86_Path -Name Minor
    }
    catch {
        $Minor = -1
    }
    $Version = $Major;
    if ($Minor -ge 0) {
        $Version += ".$Minor"
    }
    Write-Host
    Write-Host ($FoundMessage -f $Version)
    Write-Host
    if ($InteractiveMode) {
        Pause
    }
    return
}

# Check if installed.
$HklmBasePath = 'HKLM:\SOFTWARE\Classes\Installer\Dependencies'
#$HkcrBasePath = 'HKCR:\Installer\Dependencies\VC,redist.x86,x86,14.{0},bundle\Dpendents'
$HkcrBasePath = "$HklmBasePath\VC,redist.x86,x86,14.{0},bundle\Dependents"

$KeyHash = @{
    "14.0" = "$HklmBasePath\{e2803110-78b3-4664-a479-3611a381656a}" #2015
    "14.16" = "$($HkcrBasePath -f '16')\{67f67547-9693-4937-aa13-56e296bd40f6}" #2017
    "14.21" = "$($HkcrBasePath -f '21')\{49697869-be8e-427d-81a0-c334d1d14950}" #2019 14.21
    "14.22" = "$($HkcrBasePath -f '22')\{5bfc1380-fd35-4b85-9715-7351535d077e}" #2019 14.22
    "14.24" = "$($HkcrBasePath -f '24')\{e31cb1a4-76b5-46a5-a084-3fa419e82201}" #2019 14.24
    "14.36" = "$($HkcrBasePath -f '36')\{410c0ee1-00bb-41b6-9772-e12c2828b02f}" #2022
}

function IsInstalled {
    $KeyHash.Keys | ForEach-Object {
        Write-Host $KeyHash[$_]
        $FoundKey = Test-Path $KeyHash[$_]
        if ($FoundKey) {
            return $_
        }
    }
}

$NotFoundMessage = 'Not found: Cannot confirm that VC++ Redistributable 2015 is installed.'
$Message = '';
Write-Host 'Checking known registry locations for installation...'
$Version = IsInstalled
if ($Version) {
    $Message = $FoundMessage -f $Version
}
else {
    $Message = $NotFoundMessage
}

Write-Host
Write-Host "$Message"
Write-Host

if ($InteractiveMode) {
    Pause
}
