# NSClient++ INI command:
#
#certificatecheck = cmd /c echo scripts\CertificateCheck.ps1; exit($lastexitcode) | powershell.exe -command -
[cmdletbinding()]
param(
    $Warning = '90', #days
    $Critical = '30' #days
)

$result = "OK"
$exitcode = 0

$certificates = Get-ChildItem 'Cert:\LocalMachine\My','Cert:\LocalMachine\TrustedPeople' 
if($certificates -eq $null) {
    Write-Output $result
    exit $exitcode
}

$certificatesCritical = @($certificates | Where-Object { $_.NotAfter -lt (Get-Date).AddDays($Critical) }).Count
$certificatesWarning = @($certificates | Where-Object { $_.NotAfter -lt (Get-Date).AddDays($Warning) }).Count

if($certificatesWarning -gt 0) { 
    Write-Verbose "certificatesWarning:$certificatesWarning"
    $result = "WARNING - $certificatesWarning certificate(s) expiring within $Warning days" 
    $exitcode = 1

    if($certificatesCritical -gt 0) {
        Write-Verbose "certificatesCritical:$certificatesCritical"
        $result = "CRITICAL - $certificatesCritical certificate(s) expiring within $Critical days ($certificatesWarning within $Warning days)`n"
        $exitcode = 2
    }

    $result += foreach($certificate in ($certificates | Where-Object { $_.NotAfter -lt (Get-Date).AddDays($Warning) })) {
        $subject = $certificate.Subject
        Write-Verbose ". subject:$subject"
        Write-Verbose ($certificate | fl * | Out-String)

        $date = Get-Date $certificate.NotAfter -Format 'yyyy-MM-dd HH:mm:ss'
        $cnIndex = $subject.IndexOf('CN=')
        if($cnIndex -ne -1) {
            $commaIndex = $subject.IndexOf(',', $cnIndex)
            if($commaIndex -ne -1) {
                Write-Output "`n$date - $($subject.Substring($cnIndex, $commaIndex-$cnIndex))"
            }
            else {
                Write-Output "`n$date - $($subject.Substring($cnIndex))"
            }
        }
        else {
            Write-Output "`nCN="
        }
    }
}

Write-Output $result
exit $exitcode