#!/bin/bash

set -e

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

# Check for one non-empty source code file in the crate
# Returns 0 if the crate is a stub
is_stub() {
    crate_path="$1"

    # Check lib.rs directly
    if [[ -f "$crate_path/lib.rs" && -s "$crate_path/lib.rs" ]]; then
        return 1
    fi

    src_dir="$crate_path/src"

    # If the crate doesn't have an src/ dir, then it's not a stub. All
    # the stubs follow the same format.
    if ! [[ -d "$src_dir" ]]; then
        return 0
    fi

    # Look for any non-empty file in src/
    while IFS= read -r -d '' file; do
        if [[ -s "$file" ]]; then
            return 1
        fi
    done < <(find "$src_dir" -maxdepth 1 -type f -print0)
    return 0
}

to_lintian_override() {
    crate_path="$1"
    echo "$pkg_name source: file-without-copyright-information vendor/$(basename "$crate_path")/* [debian/copyright]"
}

stub_list() {
    stubs_dir="$1"
    for crate in "$stubs_dir"/*; do
        [[ -d "$crate" ]] || continue

        if is_stub "$crate"; then
            echo "$(to_lintian_override "$crate")"
        fi
    done
}

pkg_name=$(sed -n 's/^Source: \(rustc-[0-9][0-9.]\+\).*/\1/p' debian/control)

script_dir=$(dirname "$(dirname "$(readlink -f "$0")")")
vendor_dir="$script_dir/vendor"
temp_name="lintian-overrides.stubbed-crates"
temp_path="$script_dir/debian/source/$temp_name"

header='# AUTOGENERATED START'
footer='# AUTOGENERATED END'
{
    echo "$header"
    stub_list "$vendor_dir"
    echo "$footer"
} >"$temp_path"

cd "$script_dir/debian/source"

sed -i -e "/^$header/,/^$footer/d" -e '/^# Crate stubs/rlintian-overrides.stubbed-crates' lintian-overrides
