# Setup-Inbox.ps1 (v3 pack, 2026-08-19) — every-install step: create the standard
# ImageAnywhere inbox folder and let the app adopt it by itself — zero in-app clicks
# on app versions that have inbox auto-adopt (releases after 1.9.302.5).
# Double-click 1-Setup-Inbox.cmd. Safe to re-run: every step skips what already exists.
#
# What it does:
#   1. Allows ImageAnywhere's "File system" permission (Settings > Privacy) for the
#      CURRENT user, so the app can reach C:\unified_imaging\inbox and adopt it
#      automatically at next launch. Runs BEFORE elevation on purpose: the permission
#      lives in the signed-in operator's registry hive, not the admin's.
#   2. Creates C:\unified_imaging\inbox (the standard inbox root for every install).
#   3. Grants normal users write access to the whole C:\unified_imaging tree so device
#      accounts and tools never hit permission walls.
#   4. Prints the fallback card: on app versions without auto-adopt (1.9.302.5 and
#      older), or if the permission could not be set, the operator picks the folder
#      inside the app exactly as before.
#
# Device subfolders (nw500, nw400, ...) are created by the app when a device is
# configured, or by 3-Setup-CameraShare-Apply.cmd for shared-folder cameras.

param(
    [switch]$DryRun,
    [switch]$Elevated,
    [string]$InboxRoot = 'C:\unified_imaging\inbox'
)

$ErrorActionPreference = 'Stop'

function Step([string]$label, [scriptblock]$work) {
    try { & $work; Write-Host ("  OK   " + $label) }
    catch { Write-Host ("  FAIL " + $label + " -> " + $_.Exception.Message) }
}
function Pause-IfInteractive([string]$msg) {
    try { Read-Host $msg | Out-Null } catch { }
}

# --- Permission pre-allow (operator hive; skipped in the elevated re-run) ---------
# Writes what the Settings > Privacy & security > File system toggle writes. HKCU
# needs no admin, so this works in the plain double-click context. If the app isn't
# installed yet the family name can't be resolved; re-running after install fixes
# it, and the worst case is only the old in-app picker card.
if (-not $Elevated) {
    # Exact name on purpose: *ImageAnywhere* also matches LocalAlpha/ModernSpike side installs.
    $pkg = Get-AppxPackage -Name UnifiedImaging.ImageAnywhere | Select-Object -First 1
    if ($DryRun) {
        if ($pkg) { Write-Host ("Would allow File system permission for " + $pkg.PackageFamilyName) }
        else      { Write-Host 'Would allow File system permission (ImageAnywhere not installed yet - would skip)' }
    } elseif ($pkg) {
        Step ('File system permission allowed for ' + $pkg.Name) {
            $store = 'HKCU:\Software\Microsoft\Windows\CurrentVersion\CapabilityAccessManager\ConsentStore\broadFileSystemAccess'
            if (-not (Test-Path $store)) { New-Item -Path $store -Force | Out-Null }
            Set-ItemProperty -Path $store -Name Value -Value 'Allow'
            $appKey = Join-Path $store $pkg.PackageFamilyName
            if (-not (Test-Path $appKey)) { New-Item -Path $appKey -Force | Out-Null }
            Set-ItemProperty -Path $appKey -Name Value -Value 'Allow'
        }
    } else {
        Write-Host '  SKIP File system permission (ImageAnywhere not installed yet - re-run this script after installing it)'
    }
}

$isAdmin = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
if (-not $DryRun -and -not $isAdmin) {
    $relaunch = '-NoProfile -ExecutionPolicy Bypass -File "' + $MyInvocation.MyCommand.Path + '" -Elevated'
    Start-Process powershell -Verb RunAs -ArgumentList $relaunch
    exit
}

Write-Host ''
if ($DryRun) { Write-Host '=== PREVIEW ONLY - nothing will be changed ===' }
else { Write-Host '=== ImageAnywhere inbox setup (changes will be applied) ===' }
Write-Host ''

$parent = Split-Path $InboxRoot -Parent

if (Test-Path $InboxRoot) {
    Write-Host ("Inbox folder already exists: " + $InboxRoot)
} elseif ($DryRun) {
    Write-Host ("Would create " + $InboxRoot)
} else {
    Step ("inbox folder " + $InboxRoot) {
        New-Item -ItemType Directory -Force -Path $InboxRoot | Out-Null
    }
}

if ($DryRun) {
    Write-Host ("Would grant normal users write access on " + $parent)
} else {
    Step ("write access for normal users on " + $parent) {
        icacls $parent /grant 'Users:(OI)(CI)M' | Out-Null
        if ($LASTEXITCODE -ne 0) { throw 'icacls failed' }
    }
}

Write-Host ''
Write-Host '======================================================'
Write-Host ' Now open ImageAnywhere. On current app versions'
Write-Host ' (after 1.9.302.5) it adopts the inbox by itself -'
Write-Host ' nothing to click.'
Write-Host ''
Write-Host ' Older app version, or the app still asks? Do this:'
Write-Host '   1. When the "Inbox Not Set" dialog appears, click'
Write-Host '      Continue. (Already past it? Use Config instead.)'
Write-Host ("   2. In the folder picker, go to " + $InboxRoot)
Write-Host '      and click "Select Folder".'
Write-Host '======================================================'
Write-Host ''
if (-not $DryRun) { Pause-IfInteractive 'Press Enter to close' }
