#!/usr/bin/env bash

set -euo pipefail

CARGO_ABOUT_VERSION="0.7"
OUTPUT_FILE="${1:-$(pwd)/assets/licenses.md}"
TEMPLATE_FILE="script/licenses/template.md.hbs"

fail_on_stderr() {
    local tmpfile=$(mktemp)
    "$@" 2> >(tee "$tmpfile" >&2)
    local rc=$?
    [ -s "$tmpfile" ] && rc=1
    rm "$tmpfile"
    return $rc
}

echo -n "" >"$OUTPUT_FILE"

{
    echo -e "# ###### THEME LICENSES ######\n"
    cat assets/themes/LICENSES

    echo -e "\n# ###### ICON LICENSES ######\n"
    cat assets/icons/LICENSES

    echo -e "\n# ###### CODE LICENSES ######\n"
} >>"$OUTPUT_FILE"

if ! cargo about --version | grep "cargo-about $CARGO_ABOUT_VERSION" &>/dev/null; then
    echo "Installing cargo-about@^$CARGO_ABOUT_VERSION..."
    cargo install "cargo-about@^$CARGO_ABOUT_VERSION"
else
    echo "cargo-about@^$CARGO_ABOUT_VERSION is already installed."
fi

echo "Generating cargo licenses"
if [ -z "${ALLOW_MISSING_LICENSES-}" ]; then FAIL_FLAG=--fail; else FAIL_FLAG=""; fi
if [ -z "${ALLOW_MISSING_LICENSES-}" ]; then WRAPPER=fail_on_stderr; else WRAPPER=""; fi
set -x
$WRAPPER cargo about generate \
    $FAIL_FLAG \
    -c script/licenses/zed-licenses.toml \
    "$TEMPLATE_FILE" >>"$OUTPUT_FILE"
set +x

sed -i.bak 's/&quot;/"/g' "$OUTPUT_FILE"
sed -i.bak 's/&#x27;/'\''/g' "$OUTPUT_FILE" # The ` '\'' ` thing ends the string, appends a single quote, and re-opens the string
sed -i.bak 's/&#x3D;/=/g' "$OUTPUT_FILE"
sed -i.bak 's/&#x60;/`/g' "$OUTPUT_FILE"
sed -i.bak 's/&lt;/</g' "$OUTPUT_FILE"
sed -i.bak 's/&gt;/>/g' "$OUTPUT_FILE"

rm -rf "${OUTPUT_FILE}.bak"

echo "generate-licenses completed. See $OUTPUT_FILE"
