#!/bin/bash

# shlib-collision-watchdog -- break the build if two version of a
# library accidentally get linked into the same address space

# Note: ld already warns about this, but not in a way that can be used
# to break the build thus rendering it rather useless:
# /usr/bin/ld: warning: libbctoolbox.so.1, needed by /lib/x86_64-linux-gnu/libbcmatroska2.so.5, may conflict with libbctoolbox.so.2

set -e

executable="$1"

libs="$(mktemp)"
trap "rm -f $libs" EXIT INT QUIT TERM
f1="$(mktemp)"
trap "rm -f $libs $f1" EXIT INT QUIT TERM
f2="$(mktemp)"
trap "rm -f $libs $f1 $f2" EXIT INT QUIT TERM

ldd "$executable" | grep ' => ' | sed 's@ => .*$@@'|tr -d '\t '|sort > "$libs"
sed 's@\.so\..*$@@' "$libs" > "$f1"
uniq < "$f1" > "$f2"

rc=0
if ! cmp --quiet "$f1" "$f2" ; then
    echo "Error: more than one version of a library is being loaded into ${executable}:"
    for f in $(diff -U "$(wc -l < "$libs")" "$f1" "$f2" | sed -n '3,$p'| sed -n '/^-/s@@@p' ); do
        grep -e "$f" "$libs";
    done
    rc=1
fi

exit $rc
