[CmdletBinding()]
param([string]$Manifest,[string]$RuntimeManifest,[string]$HardwareManifest,[string]$Output)

$ErrorActionPreference = 'Stop'
$scriptRoot = Split-Path -Parent $MyInvocation.MyCommand.Path
$repo = Split-Path -Parent (Split-Path -Parent $scriptRoot)
$projectDeclaration = Get-Content -LiteralPath (Join-Path $repo 'CMakeLists.txt') -Raw
if ($projectDeclaration -notmatch 'project\(SmartCut64 VERSION ([0-9]+\.[0-9]+\.[0-9]+) LANGUAGES CXX\)') {
  throw 'Could not determine the SmartCut64 project version from CMakeLists.txt'
}
$version = $Matches[1]
if ([string]::IsNullOrWhiteSpace($Manifest)) { $Manifest = Join-Path $scriptRoot '..\manifests\m1-dependencies.json' }
if ([string]::IsNullOrWhiteSpace($RuntimeManifest)) { $RuntimeManifest = Join-Path $scriptRoot '..\manifests\runtime-dependencies.json' }
if ([string]::IsNullOrWhiteSpace($HardwareManifest)) { $HardwareManifest = Join-Path $scriptRoot '..\manifests\hardware-codec-build-packages.json' }
if ([string]::IsNullOrWhiteSpace($Output)) { $Output = Join-Path $scriptRoot '..\sbom.m1.json' }
$lock = Get-Content -LiteralPath $Manifest -Raw | ConvertFrom-Json
$components = foreach ($dependency in $lock.dependencies) {
  [pscustomobject]@{
    type='library'
    name=$dependency.name
    version=$dependency.version
    purl="pkg:generic/$($dependency.name)@$($dependency.version)"
    hashes=@([pscustomobject]@{alg='SHA-256';content=$dependency.archiveSha256.ToLowerInvariant()})
    licenses=@([pscustomobject]@{license=[pscustomobject]@{name=$dependency.license}})
  }
}
$runtimeLock = Get-Content -LiteralPath $RuntimeManifest -Raw | ConvertFrom-Json
$components += foreach ($dependency in $runtimeLock.components) {
  [pscustomobject]@{
    type='library'
    name=$dependency.name
    version=$dependency.version
    purl="pkg:generic/$($dependency.name)@$($dependency.version)"
    licenses=@([pscustomobject]@{license=[pscustomobject]@{name=$dependency.license}})
    properties=@([pscustomobject]@{name='smartcut:runtime-dlls';value=($dependency.dlls -join ',')})
  }
}
$hardwareLock = Get-Content -LiteralPath $HardwareManifest -Raw | ConvertFrom-Json
$components += foreach ($dependency in $hardwareLock.packages) {
  [pscustomobject]@{
    type='library'
    name=$dependency.name
    version=$dependency.version
    purl="pkg:generic/$($dependency.name)@$($dependency.version)"
    licenses=@([pscustomobject]@{license=[pscustomobject]@{name=$dependency.license}})
    properties=@([pscustomobject]@{name='smartcut:build-purpose';value=$dependency.purpose})
  }
}
[pscustomobject]@{
  bomFormat='CycloneDX'
  specVersion='1.5'
  version=1
  metadata=[pscustomobject]@{component=[pscustomobject]@{type='application';name='SmartCut64';version=$version}}
  components=@($components)
} | ConvertTo-Json -Depth 8 | Set-Content -LiteralPath $Output -Encoding utf8
Write-Output "Wrote $Output"
