#!/usr/bin/env bash
# Regenerate `docs/security/flutter-license-inventory.md` by
# walking `pubspec.lock` and pulling each dependency's LICENSE file
# from the local pub cache. CI checks that the committed inventory
# matches the regenerated output.

set -euo pipefail

# Allow callers to pre-set FLUTTER_HOME or simply have flutter on
# their PATH. Fall back to the developer machine default.
if ! command -v flutter >/dev/null 2>&1; then
    if [[ -n "${FLUTTER_HOME:-}" && -x "$FLUTTER_HOME/bin/flutter" ]]; then
        export PATH="$FLUTTER_HOME/bin:$PATH"
    elif [[ -x "$HOME/sdks/flutter/bin/flutter" ]]; then
        export PATH="$HOME/sdks/flutter/bin:$PATH"
    else
        echo "error: 'flutter' not on PATH and \$FLUTTER_HOME unset" >&2
        exit 1
    fi
fi

HERE="$(cd "$(dirname "$0")/.." && pwd)"
APP="$HERE/apps/chanora_flutter"
LOCK="$APP/pubspec.lock"
OUT="$HERE/docs/security/flutter-license-inventory.md"

if [[ ! -e "$LOCK" ]]; then
    echo "error: $LOCK not found; run 'flutter pub get' first" >&2
    exit 1
fi

mkdir -p "$(dirname "$OUT")"

# Ensure the pub cache is populated so the LICENSE files exist on
# disk for the Dart script to read.
(cd "$APP" && flutter pub get >/dev/null)

dart run "$HERE/tools/dump_flutter_licenses.dart" "$LOCK" "$OUT"
