$exitCodes = @{
  "UNKNOWN"    = 3;
  "CRITICAL"   = 2;
  "WARNING"    = 1;
  "OK"         = 0
}

# check if puppet agent is installed on node
$service_name = 'puppet'

try 
{
    if ((get-service -Name $service_name -ea Stop).Status -ne "Running")
    {
        Write-Host "Service state:" (get-service -Name $service_name).Status
        Exit $exitCodes.Critical
    }

}
catch
{
    Write-Host "Puppet agent is not installed."
    exit $exitCodes.Critical
}

$puppet_file = get-item 'C:\ProgramData\PuppetLabs\puppet\cache\state\last_run_summary.yaml'

# first we are going to check the age of the status file
# if it's older than 1 hour (warning) or 24 hours (critical)
$puppet_file_write_time = $puppet_file.LastWriteTime
$date_string = $puppet_file_write_time -f {MM:dd:yy}

if (((get-date) - $puppet_file_write_time).TotalHours -gt 24 )
{
    Write-Host "Last catalog run -- $date_string"
    exit $exitCodes.Critical
}
elseif (((get-date) - $puppet_file_write_time).TotalHours -gt 1 )
{
    Write-Host "Last catalog run -- $date_string"
    exit $exitCodes.Warning
}

# get all items in status yaml file pertaining to events (if they exist)
[System.Collections.ArrayList]$content = get-content $puppet_file
$index = $content.Indexof("events:")
$events = @{}

if ($index -ne -1)
{
    $range_events = $content.getRange(($index + 1),($content.count - ($index + 1)))
    
    foreach ($event in $range_events)
    {
        $event = $event.split(":")
        $events.Add($event[0].trim(),$event[1].trim())
    }

    $output_string = "Last catalog run -- " + $date_string + "; Events -- "

    foreach ($key in $events.keys) 
    {
        $output_string += $key +": " + $events[$key] + ", "
    }

    $output_string = $output_string.trimEnd(", ")

    if ($events.failure -ne 0)
    {
       Write-Host $output_string
       exit $exitCodes.Critical
    }
    else
    {
       Write-Host $output_string
       exit $exitCodes.Ok
    }
}
else
{
    Write-Host "Last catalog run -- $date_string; Catalog run failure"
    exit $exitCodes.Critical
}