<#
.SYNOPSIS
    SilentProdBatchInstall.ps1 - Automates installation or uninstallation of an application
    on multiple Fujifilm multifunction devices in batch mode.

.DESCRIPTION
    This script processes a list of devices from a CSV file and calls SilentProdInstallApp.ps1
    for each entry. It supports both installation and uninstallation operations.
    Credentials, device information, and action are passed to the underlying installer script.

    The CSV file must contain at least:
        - MfpAddress : IP or hostname of the device
        - DeviceId   : Required only when performing --install

.PARAMETER Action
    [Required] Operation to perform. Must be either:
        --install   → Installs or overwrites the application on each device.
        --uninstall → Uninstalls the application from each device.

.PARAMETER Username
    [Required] Administrator username of the target devices.

.PARAMETER Password
    [Required] Administrator password of the target devices.

.PARAMETER CsvPath
    [Required] Path to the CSV file containing device information.
    - The CSV must include a "MfpAddress" column.
    - For --install, a "DeviceId" column is also required.

.PARAMETER ServerAddress
    [Optional, required only for --install]
    Root address of the target server used for deployment.
    Passed directly to the underlying installer script.

.PARAMETER DebugLogFile
    [Optional] Path to a log file to capture installer script output.
    Passed directly to the underlying installer script.

.EXAMPLE
    .\SilentProdBatchInstall.ps1 -Action --install -CsvPath .\devices.csv -Username admin -Password 12345 -ServerAddress http://myserver.com

    Installs the application on all devices listed in devices.csv using the provided credentials and server.

.EXAMPLE
    .\SilentProdBatchInstall.ps1 -Action --uninstall -CsvPath .\devices.csv -Username admin -Password 12345

    Uninstalls the application from all devices listed in devices.csv.
#>
param(
    [Alias("act")]
    [string]$Action,

    [Alias("u")]
    [string]$Username,

    [Alias("p")]
    [string]$Password,

    [Alias("csv")]
    [string]$CsvPath,


    [Alias("srv")]
    [string]$ServerAddress,

    [Alias("log")]
    [string]$DebugLogFile
)

# Check  params
if (-not $Action -or -not $CsvPath -or -not $Username -or -not $Password) {
    Write-Error "Usage: .\SilentProdBatchInstall.ps1 -Action --install |--uninstall -CsvPath <file.csv> -Username <user> -Password <pass> [-ServerAddress <server>] [-DebugLogFile <logfile>]"
    exit 1
}

if (($Action -ne "--install") -and ($Action -ne "--uninstall")) { throw "Invalid -Action. Must be --install or --uninstall" }

# Check that CSV exists
if (-not (Test-Path $CsvPath)) {
    Write-Error "CSV file not found: $CsvPath"
    exit 1
}

# Import CSV: must contain MfpAddress and DeviceId columns
$devices = Import-Csv $CsvPath

foreach ($device in $devices) {
    $DeviceAddress = $device.MfpAddress
    $DeviceIdFromCsv = $device.DeviceId

    # Determine which credentials to use
    $DeviceUsername = if ($device.Username -and $device.Username.Trim() -ne "") { $device.Username } else { $Username }
    $DevicePassword = if ($device.Password -and $device.Password.Trim() -ne "") { $device.Password } else { $Password }


    if (-not $DeviceAddress) {
        Write-Warning "Skipping row without MfpAddress"
        continue
    }

    # Build argument list for SilentProdInstallApp.ps1
    $argsList = @(
        "-act", $Action,
        "-u", $DeviceUsername,
        "-p", $DevicePassword,
        "-mfp", $DeviceAddress
    )

    if ($Action -eq "--install") {
		
		if (-not $DeviceIdFromCsv) {
			Write-Warning "Skipping row without DeviceIdFromCsv"
			continue
		}
		
        $argsList += @("-id", $DeviceIdFromCsv, "-srv", $ServerAddress)
    }

    if ($DebugLogFile) {
        $argsList += @("-log", $DebugLogFile)
    }

    Write-Host ">>> Processing device $DeviceAddress (DeviceId=$DeviceIdFromCsv)"

    # Call the single-install script
    & powershell -NoProfile -ExecutionPolicy Bypass -File "SilentProdInstallApp.ps1" @argsList


    if ($LASTEXITCODE -ne 0) {
        Write-Error "[FAILED] Device $DeviceAddress (DeviceId=$DeviceIdFromCsv)"
    } else {
        Write-Host "[SUCCESS] Device $DeviceAddress (DeviceId=$DeviceIdFromCsv)"
    }
}
