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

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
OUT_FILE="$ROOT_DIR/crates/gitcomet-ui-gpui/assets/open_source_licenses.tsv"
TMP_FILE="$(mktemp)"

cleanup() {
  rm -f "$TMP_FILE"
}
trap cleanup EXIT

cargo metadata --format-version 1 --locked > "$TMP_FILE"

{
  echo "# Generated by scripts/generate-open-source-licenses.sh"
  jq -r '
    .packages
    | map(select(.source != null))
    | sort_by(.name, .version)
    | .[]
    | [
        .name,
        .version,
        (if .license != null then .license elif .license_file != null then ("SEE " + .license_file) else "UNKNOWN" end)
      ]
    | @tsv
  ' "$TMP_FILE"
} > "$OUT_FILE"

echo "Wrote $(wc -l < "$OUT_FILE") lines to $OUT_FILE"
