param(
    [string]$Destination = "$(Join-Path (Split-Path -Parent $PSCommandPath) '..' | Resolve-Path)/seed-data/ics-cisa"
)

$ErrorActionPreference = 'Stop'
New-Item -Path $Destination -ItemType Directory -Force | Out-Null

Function Write-Info($Message) { Write-Host "[ics-seed] $Message" }
Function Write-ErrorLine($Message) { Write-Host "[ics-seed][error] $Message" -ForegroundColor Red }

Function Download-File($Url, $Path) {
    Write-Info "Downloading $(Split-Path $Path -Leaf)"
    Invoke-WebRequest -Uri $Url -OutFile $Path -UseBasicParsing
    $hash = Get-FileHash -Path $Path -Algorithm SHA256
    $hash.Hash | Out-File -FilePath "$Path.sha256" -Encoding ascii
}

$base = 'https://raw.githubusercontent.com/icsadvprj/ICS-Advisory-Project/main/ICS-CERT_ADV'
$master = 'CISA_ICS_ADV_Master.csv'
$snapshot = 'CISA_ICS_ADV_2025_10_09.csv'

Write-Info 'Fetching ICS advisories seed data (ODbL v1.0)'
Download-File "$base/$master" (Join-Path $Destination $master)
Download-File "$base/$snapshot" (Join-Path $Destination $snapshot)

$medicalUrl = 'https://raw.githubusercontent.com/batarr22/ICSMA_CSV/main/ICSMA_CSV_4-20-2023.xlsx'
$medicalFile = 'ICSMA_CSV_4-20-2023.xlsx'
Write-Info 'Fetching community ICSMA snapshot'
try {
    Download-File $medicalUrl (Join-Path $Destination $medicalFile)
}
catch {
    Write-ErrorLine "Unable to download $medicalFile (optional): $_"
    Remove-Item (Join-Path $Destination $medicalFile) -ErrorAction SilentlyContinue
}

Write-Info "Seed data ready in $Destination"
Write-Info 'Remember: data is licensed under ODbL v1.0 (see seed README).'
