#!/bin/bash
# Copyright © 2019-2023 Collabora Ltd.
# SPDX-License-Identifier: BSD-3-Clause

# Not using ${//} bashism for simplicity
# shellcheck disable=SC2001

set -e
set -u

echo "TAP version 13"

num_tests=0
failed=

diff_output () {
    left="$1"
    left_output="$2"
    right="$3"
    right_output="$4"

    echo "# --- $left"
    echo "# +++ $right"
    echo "$left_output" | sed -e 's/^/# -/'
    echo "$right_output" | sed -e 's/^/# +/'
}

ok () {
    num_tests=$(( num_tests + 1 ))
    echo "ok $num_tests $*"
}

not_ok () {
    num_tests=$(( num_tests + 1 ))
    echo "not ok $num_tests $*"
    failed=1
}

for tool in \
    addr2line \
    ar \
    as \
    c++filt \
    dwp \
    elfedit \
    gold \
    gprof \
    ld \
    ld.bfd \
    ld.gold \
    nm \
    objcopy \
    objdump \
    ranlib \
    readelf \
    size \
    strings \
    strip \
; do
    if ver=$("${tool}-2.35" --version 2>&1); then
        ok "${tool}-2.35 --version"
    else
        echo "$ver" | sed -e 's/^/# /'
        not_ok "${tool}-2.35 --version"
    fi

    if other=$("/usr/lib/binutils-2.35/bin/${tool}" --version 2>&1); then
        if [ "$other" = "$ver" ]; then
            ok "/usr/lib/binutils-2.35/bin/${tool} --version"
        else
            diff_output "${tool}-2.35" "$ver" \
                "/usr/lib/binutils-2.35/bin/${tool}" "$other"
            not_ok "${tool} --version output differs"
        fi
    else
        echo "$other" | sed -e 's/^/# /'
        not_ok "/usr/lib/binutils-2.35/bin/${tool} --version"
    fi

    case "$(dpkg --print-architecture)" in
        (amd64)
            gnu_type=x86_64-linux-gnu
            ;;
        (i386)
            gnu_type=i686-linux-gnu
            ;;
        (*)
            continue
            ;;
    esac

    if ver=$("${gnu_type}-${tool}-2.35" --version 2>&1); then
        ok "${gnu_type}-${tool}-2.35 --version"
    else
        echo "$ver" | sed -e 's/^/# /'
        not_ok "${gnu_type}-${tool}-2.35 --version"
    fi

    if ver=$("/usr/lib/binutils-2.35/bin/${gnu_type}-${tool}" --version 2>&1); then
        ok "/usr/lib/binutils-2.35/bin/${gnu_type}-${tool} --version"
    else
        echo "$ver" | sed -e 's/^/# /'
        not_ok "/usr/lib/binutils-2.35/bin/${gnu_type}-${tool} --version"
    fi
done

ver="$(ld.bfd-2.35 --version)"
other="$("/usr/lib/compat-ld-2.35/ld" --version)"

if [ "$ver" = "$other" ]; then
    ok "/usr/lib/compat-ld-2.35/ld --version"
else
    not_ok "/usr/lib/compat-ld-2.35/ld --version"
fi

ver="$(ld.gold-2.35 --version)"
other="$("/usr/lib/gold-ld-2.35/ld" --version)"

if [ "$ver" = "$other" ]; then
    ok "/usr/lib/gold-ld-2.35/ld --version"
else
    not_ok "/usr/lib/gold-ld-2.35/ld --version"
fi

echo "1..$num_tests"

if [ -n "$failed" ]; then
    exit 1
fi

# vim:set sw=4 sts=4 et ft=sh:
