# This script reads the Parsec log in a VM, parses it and returns all connect/disconnect entries present

param(
    [Parameter(Mandatory = $true)]
    [string]$vmName,
    [Parameter(Mandatory = $true)]
    [string]$vmPassword
)

Set-Location $PSScriptRoot
.("..\AOFLibrary\AOFLibrary.ps1")

$ScriptName = "GetParsecLoginHistory"
$LogFile = BeginScriptLogging -ScriptName $ScriptName

$password = ConvertTo-SecureString $vmPassword -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential ("Administrator", $password)

try {
    $rawRelevantEntries = Invoke-Command -VMName $vmName -Credential $cred -ScriptBlock {
        $fileContent = Get-Content -Path "C:\ProgramData\Parsec\log.txt" -Raw
        $logPattern = "\[I.*connected"
        $parsedLog = [regex]::Matches($fileContent, $logPattern)
        $rawRelevantEntries = New-Object Collections.Generic.List[string]
        foreach($logEntry in $parsedLog.Groups)
        {
            $rawRelevantEntries.Add($logEntry.Value)
        }
        return $rawRelevantEntries
    } -ErrorAction Stop
}
catch 
{
    HandleScriptExecutionError -Message "Unable to get login history: $($PSItem.Exception.message)" -Log $LogFile
}

$entryDateFormat = "yyyy-MM-ddTHH:mm:ss" # "dd.MM.yyyy HH:mm"
function Parse-Date($date)
{
    return (Get-Date -Date $date).ToString($entryDateFormat)
}

$entryObjects = @()
$logEntryPattern = "\[\w\s(?<date>\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})\]\s+(?<user>[^\s]+)\s+(?<event>connected|disconnected)"
if($rawRelevantEntries)
{
    $parsedLogEntry = [regex]::Matches($rawRelevantEntries, $logEntryPattern)
    foreach($entryInformation in $parsedLogEntry)
    {
        [PSCustomObject]$entryObject = @{
            "Date" = (Parse-Date -date $entryInformation.Groups["date"].Value)
            "User" = $entryInformation.Groups["user"].Value
            "Connected" = ($entryInformation.Groups["event"].Value -eq "connected")
        }
        $entryObjects += $entryObject
    }

    if($entryObjects.Count -ne 1)
    {
        Write-Log -Message ($entryObjects | ConvertTo-Json) -Level INFO -Log $LogFile
    }
    else
    {
        Write-Log -Message "[ $($entryObjects | ConvertTo-Json) ]" -Level INFO -Log $LogFile # ConvertTo-Json would otherwise not return an array
    }
}
else
{
    Write-Log -Message "[ { } ]" -Level INFO -Log $LogFile # ConvertTo-Json would otherwise return an empty object
}

Write-ScriptSuccess -Log $LogFile
