# Syncro Script: Update ScreenConnect Session Properties via RESTful API
#
# Runs on each machine to self-report its company/device info to ScreenConnect.
# Designed to run on a schedule (e.g., daily) alongside other maintenance scripts.
#
# Syncro Platform Variables (set in script editor):
#   $OrgName      - platform - {{customer_business_name_or_customer_name}}
#
# File Type: PowerShell | Run as: System | Max Run Time: 5 minutes

Import-Module $env:SyncroModule

# ============================================================================
# Configuration
# ============================================================================

$SCBaseUrl    = "https://computerguru.screenconnect.com"
$SCExtGuid    = "2d558935-686a-4bd0-9991-07539f5fe749"
$SCAuthSecret = "FTnl15dK1uaKCOeFzkO1UnjGqpgtqCA5vRExWeXT38LjAV4vF9W/mYf8GpCyqlAv"

# ============================================================================
# Check if ScreenConnect is installed
# ============================================================================

$SCService = Get-Service -Name "ScreenConnect Client*" -ErrorAction SilentlyContinue
if (-not $SCService) {
    Write-Host "ScreenConnect not installed - skipping."
    exit 0
}

# ============================================================================
# Extract session GUID from service name
# ============================================================================

# Service name format: "ScreenConnect Client (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx)"
$guidMatch = $SCService.Name | Select-String -Pattern '\(([0-9a-f\-]{36})\)' -AllMatches
if (-not $guidMatch -or -not $guidMatch.Matches) {
    Write-Host "Could not extract session GUID from service: $($SCService.Name)"
    exit 1
}

$SessionGuid = $guidMatch.Matches[0].Groups[1].Value
Write-Host "SC Session GUID: $SessionGuid"

# ============================================================================
# Determine device type
# ============================================================================

$DeviceType = "Desktop"
try {
    $chassis = (Get-CimInstance -ClassName Win32_SystemEnclosure).ChassisTypes
    if ($chassis | Where-Object { $_ -in @(8,9,10,11,12,14,18,21,31,32) }) { $DeviceType = "Laptop" }
    if ($chassis | Where-Object { $_ -in @(17,23) }) { $DeviceType = "Server" }
    $model = (Get-CimInstance -ClassName Win32_ComputerSystem).Model
    if ($model -match "Virtual|VMware|VirtualBox|Hyper-V|KVM|Xen") { $DeviceType = "Virtual $DeviceType" }
} catch {
    Write-Host "Could not detect device type, defaulting to Desktop"
}

# ============================================================================
# Build and send API request
# ============================================================================

$Company = if ([string]::IsNullOrWhiteSpace($OrgName)) { "Unassigned" } else { $OrgName }

Write-Host "Updating SC: Company='$Company', DeviceType='$DeviceType', Tag='Syncro-Matched'"

# CP1=Company, CP2=Site, CP3=Department, CP4=DeviceType, CP5=Tag, CP6-8=blank
$body = ConvertTo-Json @(
    $SessionGuid,
    @($Company, "", "", $DeviceType, "Syncro-Matched", "", "", "")
) -Compress

$url = "$SCBaseUrl/App_Extensions/$SCExtGuid/Service.ashx/UpdateSessionCustomProperties"

try {
    $response = Invoke-WebRequest -Uri $url -Method POST -Body $body -ContentType "application/json" -Headers @{
        "CTRLAuthHeader" = $SCAuthSecret
        "Origin"         = $SCBaseUrl
    } -UseBasicParsing -ErrorAction Stop

    if ($response.StatusCode -eq 200) {
        Write-Host "Success - SC session updated."
        Log-Activity -Message "SC Properties: $Company / $DeviceType" -EventName "ScreenConnect"
    } else {
        Write-Host "Unexpected status: $($response.StatusCode)"
        Write-Host $response.Content
    }
} catch {
    $err = $_.Exception.Message
    Write-Host "API call failed: $err"
    Log-Activity -Message "SC Properties FAILED: $err" -EventName "ScreenConnect"
    exit 1
}
