#!/hint/bash
# SPDX-FileCopyrightText: 2024-2025 Eli Schwartz <eschwartz@gentoo.org>
# SPDX-License-Identifier: GPL-2.0-or-later

cargo_vendored_code() {
    has cargo ${INHERITED} || return 0
    # not guaranteed by PMS?
    if [[ -z ${S} || ! -d ${S} ]]; then
        eqawarn "Failed to QA: no accessible workdir (${S})"
        return 0
    fi

    local line crate dir
    local -A crates evildeps

    if has debug ${USE}; then
        local typ=debug
    else
        local typ=release
    fi
    local -a cratedirs=()
    if has rust-toolchain ${INHERITED}; then
        mapfile -d '' -O "${#cratedirs[@]}" -t cratedirs < <(find "${WORKDIR}" -regex ".*/target/$(rust_abi)/${typ}" -print0)
    fi
    mapfile -d '' -O "${#cratedirs[@]}" -t cratedirs < <(find "${WORKDIR}" -regex ".*/target/${typ}" -print0)

    for dir in "${cratedirs[@]}"; do
        if ! [[ -d ${dir}/build && -d ${dir}/.fingerprint && -d ${dir}/deps ]]; then
            eqawarn "Found what looked like a cargo directory, but it is not??? Report it to Eli."
            eqawarn "----> ${dir}"
            continue
        fi
        while read -rd '' line; do
            line=${line#*/build/}
            crate=${line%%/*}
            crate=${crate%-*}

            case ${line} in
                # rust codegen unit -- build.rs compiled a raw *.rs file
                *.rcgu.o)
                continue;;
            esac

            case ${crate} in
                # specialized code written exclusively for embedding in rust
                # technically could be forked from bash even harder, to support
                # installing as a system lib. Don't warn.
                scallop)
                    continue;;
                # stub binding code
                cryptography-cffi)
                    continue;;
                # does not offer devendor option, so warn separately.
                ring|blake3)
                    evildeps["${crate}"]="yes"
                    continue;;
            esac

        if [[ -n ${crates["${crate}"]} ]]; then
            crates["${crate}"]+=" ${line##*/}"
        else
            crates["${crate}"]="${line##*/}"
        fi
        done < <(find "${dir}" -name '*.o' -print0)
    done

    if [[ -n "${crates[@]}" ]]; then
        eqawarn "QA Notice: cargo built package contains possibly vendored code"
        eqawarn
        for crate in "${!crates[@]}"; do
            eqawarn "crate ${crate}: ${crates["${crate}"]}"
        done
        printf '\n'
    fi
    if [[ -n "${evildeps[@]}" ]]; then
        eqawarn "QA Notice: cargo built package contains possibly vendored code from unsolvable crates"
        eqawarn
        eqawarn "${!evildeps[*]}"
    fi
}

cargo_vendored_code
: # guarantee successful exit
