# license.ps1
# Scans the handed folders for info.json and LICENSE files,
# then compiles them into a NOTICE.TXT file.

param (
    [Parameter(Mandatory = $true, Position = 0)]
    [string]$OutputFile,              # First argument: NOTICE.TXT

    [Parameter(Mandatory = $true, Position = 1)]
    [string]$FilesFile,              # Second argument: out_files

    [Parameter(ValueFromRemainingArguments = $true, Position = 2)]
    [string[]]$FoldersToScan
)

# Exit if no folders were provided
if (-not $FoldersToScan -or $FoldersToScan.Count -eq 0) {
    Write-Host "License: no folders specified. Exiting without generating NOTICE.TXT"
    exit 0
}

# Remove duplicates (case-insensitive by default)
$FoldersToScan = $FoldersToScan | Sort-Object -Unique

# Start NOTICE.TXT header
$header = @"
================================================================================
NOTICE
================================================================================

This product includes software developed by other organizations.
The following is a list of all third-party software components and their licenses.
"@

Set-Content -Path $OutputFile -Value $header -Encoding UTF8

$counter = 1

foreach ($root in $foldersToScan) {
    if (Test-Path $root) {
        # Recursively find info.json
        Get-ChildItem -Path $root -Recurse -Filter "info.json" | ForEach-Object {
            $infoPath = $_.FullName
            try {
                $json = Get-Content $infoPath -Raw -Encoding UTF8 | ConvertFrom-Json
            } catch {
                Write-Warning "License: skipping invalid JSON file: $infoPath"
                exit 1
            }

            # Resolve license file path (relative to info.json folder)
            $licenseFilePath = Join-Path -Path $_.Directory.FullName -ChildPath $json.license.file

            if (-Not (Test-Path $licenseFilePath)) {
                Write-Warning "License: file missing for $($json.name) ($infoPath)"
                exit 1
            }

            # Read license text
            $licenseText = Get-Content $licenseFilePath -Raw -Encoding UTF8

            # Build entry
            $entry = @"

-----------

$counter.  Library Name: $($json.name)
Version: $($json.version)
License: $($json.license.type)
Download: $($json.url)

$licenseText
"@

            Add-Content -Path $OutputFile -Value $entry -Encoding UTF8
            $counter++
        }
    }
    else {
        Write-Warning "License: folder ($root) missing"
        exit 1
    }
}

Write-Host "NOTICE.TXT has been generated at: $(Resolve-Path $OutputFile)"

# -----------------------------------------------------------------------------
# Step 2: Update *_files in script directory only if ,NOTICE.TXT is missing
# -----------------------------------------------------------------------------
$content = Get-Content -Path $FilesFile -Raw -Encoding UTF8
$fileInfo = Get-Item $FilesFile

if ($content -notmatch "NOTICE\.TXT") {
    Write-Host "Updating file: $FilesFile"
    if ($fileInfo.Attributes -band [IO.FileAttributes]::ReadOnly) {
        attrib -r $FilesFile
    }

    # Append without introducing an extra newline
    [System.IO.File]::WriteAllText(
        $FilesFile,
        $content + ",NOTICE.TXT",
        [System.Text.UTF8Encoding]::new($false)
    )
} else {
    Write-Host "No update needed for: $FilesFile"
}
