#!/usr/bin/env bash
set -euo pipefail

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
DEST_DIR="${1:-$ROOT_DIR/seed-data/ics-cisa}"
mkdir -p "$DEST_DIR"

info() { printf "[ics-seed] %s\n" "$*"; }
error() { printf "[ics-seed][error] %s\n" "$*" >&2; }

download() {
  local url="$1"
  local target="$2"
  info "Downloading $(basename "$target")"
  curl -fL "$url" -o "$target"
  sha256sum "$target" > "$target.sha256"
}

BASE="https://raw.githubusercontent.com/icsadvprj/ICS-Advisory-Project/main/ICS-CERT_ADV"
MASTER_FILE="CISA_ICS_ADV_Master.csv"
SNAPSHOT_2025="CISA_ICS_ADV_2025_10_09.csv"

info "Fetching ICS advisories seed data (ODbL v1.0)"
download "$BASE/$MASTER_FILE" "$DEST_DIR/$MASTER_FILE"
download "$BASE/$SNAPSHOT_2025" "$DEST_DIR/$SNAPSHOT_2025"

MEDICAL_URL="https://raw.githubusercontent.com/batarr22/ICSMA_CSV/main/ICSMA_CSV_4-20-2023.xlsx"
MEDICAL_FILE="ICSMA_CSV_4-20-2023.xlsx"
info "Fetching community ICSMA snapshot"
if curl -fL "$MEDICAL_URL" -o "$DEST_DIR/$MEDICAL_FILE"; then
  sha256sum "$DEST_DIR/$MEDICAL_FILE" > "$DEST_DIR/$MEDICAL_FILE.sha256"
else
  error "Unable to download $MEDICAL_FILE (optional)."
  rm -f "$DEST_DIR/$MEDICAL_FILE"
fi

info "Seed data ready in $DEST_DIR"
info "Remember: data is licensed under ODbL v1.0 (see seed README)."
