#!/usr/bin/env bash
#
# License + security audit. Run from repo root.
# Backend deps live in /package.json; the Next.js app has its own under web/.

set -uo pipefail

ROOT="$(cd "$(dirname "$0")/.." && pwd)"
#
# LGPL-3.0-or-later: appears via sharp's native libvips binary (dynamically
# linked, permitted by LGPL).
# MPL-2.0: file-level copyleft. Permitted because we don't modify the MPL'd
# source files in web-push, lightningcss, etc. — only consume them as
# dependencies. If we ever fork an MPL'd file we must release that file.
ALLOWED='MIT;MIT-0;Apache-2.0;BSD-2-Clause;BSD-3-Clause;ISC;CC0-1.0;Unlicense;0BSD;Python-2.0;CC-BY-4.0;BlueOak-1.0.0;LGPL-3.0-or-later;MPL-2.0'

echo "=== Backend npm license audit ==="
cd "$ROOT"
npx --yes license-checker --production --onlyAllow "$ALLOWED" --excludePackages 'vyndr@1.0.0' || backend_failed=1

echo ""
echo "=== Web npm license audit ==="
cd "$ROOT/web"
npx --yes license-checker --production --onlyAllow "$ALLOWED" --excludePackages 'vyndr-web@1.0.0' || web_failed=1

echo ""
echo "=== Python license audit (best-effort) ==="
if command -v pip-licenses >/dev/null 2>&1; then
  pip-licenses --format=plain --with-license-file --no-license-path | head -50
else
  echo "(pip-licenses not installed — run: pip install pip-licenses)"
fi

echo ""
echo "=== Backend security audit ==="
cd "$ROOT"
npm audit --omit=dev || true

echo ""
echo "=== Web security audit ==="
cd "$ROOT/web"
npm audit --omit=dev || true

echo ""
if [[ "${backend_failed:-0}" -eq 1 || "${web_failed:-0}" -eq 1 ]]; then
  echo "License audit FAILED — review packages above."
  exit 1
fi
echo "License audit clean."
