# Syncro Script: Install ScreenConnect with Company Properties
#
# Syncro Platform Variables (set in script editor):
#   $MachineName  - platform - {{asset_name}}
#   $OrgName      - platform - {{customer_business_name_or_customer_name}}
#
# Required File:
#   ScreenConnect.ClientSetup.msi -> c:\screenconnectinstaller.msi
#   (Download from SC Admin > Build Installer > Access > Windows MSI)
#
# File Type: PowerShell | Run as: System | Max Run Time: 10 minutes

Import-Module $env:SyncroModule

$InstallerLocation = 'C:\screenconnectinstaller.msi'

# URL-encode spaces in names for SERVICE_ARGUMENTS
$MachineName = $MachineName -replace '\s','%20'
$OrgName = $OrgName -replace '\s','%20'

# Detect device type from chassis
$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%20$DeviceType" }
} catch {}

# Check if already installed
$SCService = Get-Service -Name "ScreenConnect Client*" -ErrorAction SilentlyContinue
if ($SCService) {
    Write-Host "ScreenConnect already installed: $($SCService.Name)"
    Log-Activity -Message "SC Deploy: Already installed ($($SCService.Name))" -EventName "ScreenConnect"
    exit 0
}

# Build SERVICE_ARGUMENTS with custom properties
# c=Company&c=Site&c=Department&c=DeviceType&c=Tag&c=&c=&c=
$ServiceArgs = "SERVICE_ARGUMENTS=""?e=Access&y=Guest&h=computerguru.screenconnect.com&p=443&k=BgIAAACkAABSU0ExAAgAAAEAAQCZmJAsjX2QoAvu/VF8SV7ggAxARlSj/TwgdqA8NcZgw9q+6G/FWwABU2WOeGPvRu6rA+sECP+u11d1BOp16iWA+KbkJPT93TIctreTy/BegdplEL5Bq0L3ZJcim++PLZjwYLDaIotdnOl+24JqkV75DxC1MV9dKNkz5DqS1+jNVMBvpOLY8UgPc9Io71pNIMo/rakJNlT4ofNeJiKIfuwRtgNNYKb51vSHGyFPYtHVNjDNYlJeu320yNJdN0zWwSQst/2GR3hAX8SnzJcZeROZ3HJuJc63uT0KS4ie4+4ExKaUimtfl8oAqIp4vBwiEXhm8T5RKhx9hLiJj/5shza8&c=$OrgName&c=&c=&c=$DeviceType&c=Syncro-Deploy&c=&c=&c="""

$installparams = '/i', $InstallerLocation, $ServiceArgs
$uninstallparams = '/uninstall', $InstallerLocation, '/qb'

# Install
Write-Host "Installing ScreenConnect for $OrgName ($DeviceType)..."
$exitCode = (Start-Process -FilePath msiexec.exe -ArgumentList $installparams -Wait -Passthru).ExitCode

if ($exitCode -eq 0 -or $exitCode -eq 3010) {
    Write-Host "ScreenConnect installed successfully (exit code: $exitCode)"
    Log-Activity -Message "SC Deploy: Installed for '$OrgName' ($DeviceType)" -EventName "ScreenConnect"
} else {
    Write-Host "Installation failed with exit code: $exitCode"
    Log-Activity -Message "SC Deploy FAILED: exit code $exitCode" -EventName "ScreenConnect"
    exit 1
}

# Cleanup
Remove-Item -Path $InstallerLocation -Force -ErrorAction SilentlyContinue
