[CmdletBinding()]
param(
    [string]$InstallDir = (Join-Path $env:ProgramFiles 'KIM Quest Remote')
)

$ErrorActionPreference = 'Stop'
$TargetExe = Join-Path ([System.IO.Path]::GetFullPath($InstallDir)) 'KIMQuestRemoteHost.exe'
$ConfigDir = Join-Path $env:LOCALAPPDATA 'KIMQuestRemote'
$Tailscale = Get-Command tailscale -ErrorAction SilentlyContinue
$Status = $null
if ($Tailscale) {
    try {
        $Status = (& $Tailscale.Source status --json 2>$null) | ConvertFrom-Json
    } catch {
        $Status = $null
    }
}
$Listener = Get-NetTCPConnection -LocalPort 45830 -State Listen -ErrorAction SilentlyContinue
$Rule = Get-NetFirewallRule -DisplayName 'KIM Quest Remote Host' -ErrorAction SilentlyContinue
$Address = if ($Rule) {
    @($Rule | Get-NetFirewallAddressFilter).RemoteAddress -join ','
} else {
    ''
}
$Startup = Join-Path ([Environment]::GetFolderPath('Startup')) 'KIM Remote.lnk'
$TrustedPeers = Join-Path $ConfigDir 'trusted-tailscale-peers.json'

[pscustomobject]@{
    Hostname = $env:COMPUTERNAME
    IsAdministrator = ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole(
        [Security.Principal.WindowsBuiltInRole]::Administrator
    )
    TailscaleState = if ($Status) { $Status.BackendState } else { 'Unavailable' }
    MagicDNS = if ($Status) { $Status.Self.DNSName.TrimEnd('.') } else { '' }
    TailscaleIPv4 = if ($Status) {
        @($Status.Self.TailscaleIPs | Where-Object { $_ -notmatch ':' }) -join ','
    } else {
        ''
    }
    InstalledExe = Test-Path -LiteralPath $TargetExe
    InstalledVersion = if (Test-Path -LiteralPath $TargetExe) {
        (& $TargetExe --version 2>$null)
    } else {
        ''
    }
    Listener45830 = [bool]$Listener
    ListenerProcessIds = @($Listener.OwningProcess) -join ','
    FirewallEnabled = [bool]($Rule | Where-Object Enabled -eq 'True')
    FirewallRemoteAddress = $Address
    StartupShortcut = Test-Path -LiteralPath $Startup
    TailscaleOwner = if ($Status) {
        $Owner = $Status.User."$($Status.Self.UserID)"
        "$($Owner.DisplayName) <$($Owner.LoginName)>"
    } else {
        ''
    }
    TrustedPeerRegistry = Test-Path -LiteralPath $TrustedPeers
    LocalIdentityPresent = (
        (Test-Path -LiteralPath (Join-Path $ConfigDir 'config.json')) -and
        (Test-Path -LiteralPath (Join-Path $ConfigDir 'host-cert.pem')) -and
        (Test-Path -LiteralPath (Join-Path $ConfigDir 'host-key.pem'))
    )
} | Format-List

Write-Host 'AUDIT_READ_ONLY_PASS'
