#!/usr/bin/env sh

# Prints THIRD_PARTY_LICENSES: the license, notice and patent files of each module that amp's
# binaries compile in, and of Go, whose standard library they compile in. Their licenses require
# these files to go with the binaries, so amp embeds THIRD_PARTY_LICENSES and `amp licenses` prints
# it; bin/lint checks that it's up to date. It fails if a module has no license file at its root,
# so a new dependency can't ship without one.
#
#   scripts/licenses [TARGET...] > THIRD_PARTY_LICENSES
#
# TARGET is <os>-<arch>, such as linux-amd64; by default, the targets of amp's releases
# (publish.star). It runs from any directory, and downloads the modules that the module cache
# doesn't have.

set -e -u

ROOT="$(cd "$(dirname "$0")/.." && pwd)"
[ $# -gt 0 ] || set -- darwin-arm64 darwin-amd64 linux-amd64 linux-arm64

fail() {
    echo "scripts/licenses: $1" >&2
    exit 1
}

# section TITLE DIR...: prints the license, notice and patent files at the root of each DIR under
# TITLE, by file name, so the output doesn't depend on which DIR has which file.
section() {
    title="$1"
    shift
    paths="$(
        for dir in "$@"; do
            ls "$dir" | grep -iE '^(licen[cs]e|copying|notice|patents)([.-].*)?$' | sed "s|^|$dir/|" || true
        done | awk -F/ '{print $NF "\t" $0}' | sort | cut -f2
    )"
    echo "$paths" | grep -qiE '/(licen[cs]e|copying)[^/]*$' || fail "$title has no license file in $*"
    echo "$paths" | while read -r path; do
        printf '================================================================================\n'
        printf '%s: %s\n' "$title" "$(basename "$path")"
        printf '================================================================================\n\n'
        cat "$path"
        printf '\n'
    done
}

# go list accepts any GOOS and GOARCH, so check that Go knows each target.
DIST="$(go tool dist list)"
for target in "$@"; do
    echo "$DIST" | grep -qxF "${target%-*}/${target#*-}" || fail "Go has no target $target"
done
# The targets' go lists run at the same time, each into a file of its own, which then merge in
# order; on any exit, the ones that still run stop.
LISTS="$(mktemp -d "${TMPDIR:-/tmp}/licenses.XXXXXX")"
PIDS=""
stop() {
    for pid in $PIDS; do
        kill "$pid" 2>/dev/null || true
    done
    rm -rf "$LISTS"
}
trap stop EXIT
trap 'exit 130' INT TERM
i=0
for target in "$@"; do
    i=$((i + 1))
    GOOS="${target%-*}" GOARCH="${target#*-}" go -C "$ROOT" list -deps \
        -f '{{with .Module}}{{if not .Main}}{{.Path}} {{.Version}} {{.Dir}}{{end}}{{end}}' \
        ./cmd/amp >"$LISTS/$i" &
    PIDS="$PIDS $!"
done
i=0
for target in "$@"; do
    i=$((i + 1))
    pid="$(echo "$PIDS" | cut -d' ' -f$((i + 1)))"
    wait "$pid" || fail "go list failed for $target"
done
PIDS=""
MODULES="$(cat "$LISTS"/* | sort -u)"

cat <<'EOF'
Amp's binaries include the following third-party software, under the licenses below.

EOF
# Go's own distribution has LICENSE in GOROOT; Homebrew's has it in GOROOT's parent.
GOROOT="$(go -C "$ROOT" env GOROOT)"
GODIRS="$GOROOT"
[ -e "$GOROOT/LICENSE" ] || GODIRS="$GODIRS $(dirname "$GOROOT")"
# shellcheck disable=SC2086 # GODIRS is one or two paths without spaces
section "Go" $GODIRS
echo "$MODULES" | while read -r path version dir; do
    [ -n "$path" ] || continue
    [ -n "$dir" ] || fail "$path $version isn't in the module cache"
    section "$path $version" "$dir"
done
