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

ROOT="${1:-.}"
STAMP="$(date +%Y%m%d-%H%M%S)"
EXPORT="ncrc-data-${STAMP}"

cd "$ROOT"
mkdir -p "$EXPORT/threats" "$EXPORT/evidence" "$EXPORT/sources" "$EXPORT/meta"

copy_required() {
  src="$1"
  dst="$2"
  if [ ! -f "$src" ]; then
    printf 'ERROR: required file not found: %s\n' "$src" >&2
    exit 2
  fi
  cp -p "$src" "$EXPORT/$dst"
  printf 'included  %s -> %s\n' "$src" "$dst"
}

copy_optional() {
  src="$1"
  dst="$2"
  if [ -f "$src" ]; then
    cp -p "$src" "$EXPORT/$dst"
    printf 'included  %s -> %s\n' "$src" "$dst"
  else
    printf 'optional  %s not present\n' "$src"
  fi
}

# Core threat data
copy_required "threat_register.json" "threats/threat_register.json"
copy_required "data/threats_register.json" "threats/register.json"

# Core derived correlation data
copy_required "evidence/threat_correlations.json" "evidence/threat_correlations.json"
copy_required "evidence/evidence_index.json" "evidence/evidence_index.json"
copy_optional "evidence/correlation_review.json" "evidence/correlation_review.json"
copy_optional "evidence/correlation_run.json" "evidence/correlation_run.json"

# Source collections
copy_required "zero_day_threats/zero_day.json" "sources/cves.json"
copy_required "papers_threats/papers.json" "sources/papers.json"
copy_required "github/github.json" "sources/github.json"
copy_optional "signals/signals.json" "sources/signals.json"
copy_optional "incidents/incidents.json" "sources/incidents.json"

# Known optional intelligence layers. Included only when present.
copy_optional "narratives/narratives.json" "sources/narratives.json"
copy_optional "assessments/assessments.json" "sources/assessments.json"

# Documentation generated for this release.
if [ -f "README.md" ]; then
  cp -p "README.md" "$EXPORT/README.md"
elif [ -f "/mnt/data/README.md" ]; then
  cp -p "/mnt/data/README.md" "$EXPORT/README.md"
else
  printf 'WARNING: README.md not found\n' >&2
fi

# Machine-readable release metadata.
python3 - "$EXPORT" <<'PY'
import json
import sys
from datetime import datetime, timezone
from pathlib import Path

root = Path(sys.argv[1])
files = sorted(
    str(p.relative_to(root))
    for p in root.rglob('*')
    if p.is_file() and p.name not in {'release.json', 'SHA256SUMS'}
)
metadata = {
    "name": "Automotive Cybersecurity Dashboard data release",
    "release_directory": root.name,
    "created_at": datetime.now(timezone.utc).isoformat().replace('+00:00', 'Z'),
    "threat_key": "T-xxx",
    "files": files,
    "interpretation": {
        "accepted": "Correlation meets configured acceptance criteria; it is not proof that the complete threat has materialised.",
        "review": "Potentially relevant correlation requiring expert assessment.",
        "relevance_score": "Correlation/ranking aid; not probability, CVSS severity or threat risk score."
    }
}
(root / 'meta' / 'release.json').write_text(
    json.dumps(metadata, indent=2, ensure_ascii=False) + '\n',
    encoding='utf-8'
)
PY

# Validate every exported JSON file before packaging.
while IFS= read -r -d '' json_file; do
  python3 -m json.tool "$json_file" >/dev/null
  printf 'validated %s\n' "$json_file"
done < <(find "$EXPORT" -type f -name '*.json' -print0)

# Checksums make later sharing and comparison reproducible.
(
  cd "$EXPORT"
  find . -type f ! -name SHA256SUMS -print0 \
    | sort -z \
    | xargs -0 sha256sum > SHA256SUMS
)

ARCHIVE="${EXPORT}.tar.gz"
tar -czf "$ARCHIVE" "$EXPORT"

printf '\nExport complete\n'
printf 'Directory: %s\n' "$EXPORT"
printf 'Archive:   %s\n' "$ARCHIVE"
printf 'Files:     %s\n' "$(find "$EXPORT" -type f | wc -l)"
printf '\nShare the archive plus, if desired, its checksum:\n'
sha256sum "$ARCHIVE"
