#!/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)"

# Bundled assets that are not crates at all. These head the file, ahead of the
# dependency list.
BUNDLED_ASSET_LICENSE_ROWS=(
  $'Fira Code\t6.2-103-ge50b177\tSIL OFL-1.1'
  $'IBM Plex Sans\t3.005\tSIL OFL-1.1'
  $'Lilex\t2.621\tSIL OFL-1.1'
)

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"
  printf '%s\n' "${BUNDLED_ASSET_LICENSE_ROWS[@]}"
  # Registry crates have a `source`; vendored path dependencies do not, so they
  # are picked out by manifest location instead. Reading them from the same
  # `cargo metadata` as everything else means their name, version and licence
  # come from their own Cargo.toml and cannot drift out of this file. The
  # workspace's own AGPL crates are path dependencies too, and are excluded by
  # the same test. Provenance for each vendored crate is in its Cargo.toml.
  jq -r --arg vendor_dir "$ROOT_DIR/vendor/" '
    .packages
    | map(select(.source != null or (.manifest_path | startswith($vendor_dir))))
    | 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"
