#! /bin/bash

if [ $# != 1 ]; then
    echo "No name specified" >&2
    exit 1
fi

if [ -z "$RPM_BUILD_ROOT" ]; then
    echo "No build root defined" >&2
    exit 1
fi

if [ ! -d "$RPM_BUILD_ROOT" ]; then
    echo "Invalid build root" >&2
    exit 1
fi

name=$1
abidir=usr/lib/compatibility/$name
mkdir -p $RPM_BUILD_ROOT/$abidir
pushd $RPM_BUILD_ROOT/$abidir
for full_name in $(find $RPM_BUILD_ROOT -name "*.so*") ; do
    f=`echo ${full_name##*/}`
    ff=`echo ${f%%\.so*}`
    file $full_name | grep "shared object" > /dev/null 2>&1 && abi-dumper $full_name -o $ff.dump > /dev/null 2>&1 || :
done
popd

libdir=`rpm -E %{_libdir}`
sbindir=`rpm -E %{_sbindir}`
bindir=`rpm -E %{_bindir}`
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$RPM_BUILD_ROOT/$libdir
pushd $RPM_BUILD_ROOT/$abidir
for dir in $sbindir $bindir ; do
    if [ ! -d $RPM_BUILD_ROOT/$dir ]; then
        continue
    fi
    for f in $(ls $RPM_BUILD_ROOT/$dir) ; do
        full_name=$RPM_BUILD_ROOT/$dir/$f
        if file $full_name | grep executable > /dev/null 2>&1; then
            if timeout 5 $full_name --help > /dev/null 2>&1; then
                $full_name --help > $f-option.list
            elif timeout 5 $full_name -help > /dev/null 2>&1; then
                $full_name -help > $f-option.list
            elif timeout 5 $full_name help > /dev/null 2>&1; then
                $full_name help > $f-option.list
            elif timeout 5 $full_name -h > /dev/null 2>&1; then
                $full_name -h > $f-option.list
            fi
        fi
    done
done

# check for unexpected files
pushd $RPM_BUILD_ROOT/$abidir
for f in $(ls)
do
    # check buildroot in abi/api files
    if cat $f | grep "BUILDROOT" > /dev/null 2>&1; then
        sed -e '/BUILDROOT/d' $f > $f.new
        mv $f.new $f
    fi
    # remove unexpected files or directories
    echo "$f" | grep -q -E '\.dump$' || echo "$f" | grep -q -E '\-option.list$' || rm -rf ./$f
done
popd
