#!/bin/bash
lib=$1
outdir=${lib%/*}
outdir=${outdir/lib64/share\/abi}
RPM_MAX_ABIDW_TIME=${RPM_MAX_ABIDW_TIME:-300}

test -e /usr/bin/abidw || exit 0
test -e /usr/bin/readelf || exit 0

if [ -L "$lib" ]; then
    # Skip symlinks, we operate only on the actual library file
    exit 0
fi

check_lib() {
    if [ -z "$soname" ]; then
        echo >&2 "$lib: library has no SONAME, refusing to create ABI dump"
        return 1
    fi

    # do not process libraries that are compiled from fortran, until the
    # upstream issue is fixed: https://sourceware.org/bugzilla/show_bug.cgi?id=23905
    if readelf -d "${lib}" | grep -q \(NEEDED\).*libgfortran\.so; then
        1>&2 echo "$lib: suspect fortran, refusing to create ABI dump"
        return 1
    fi
}

# Get the library SONAME to calculate the file path
soname=`/usr/bin/readelf -d "$lib" 2>/dev/null | perl -n -e 'print $1 if /\(SONAME\) .*\[(.*)\]/'`

check_lib || exit 0

out=$outdir/$soname.abi

mkdir -p "$outdir"

/usr/bin/abidw --no-corpus-path --no-show-locs \
     --clr-max-runtime $RPM_MAX_ABIDW_TIME \
     --out-file "$out" "$lib"
r=$?
if [ $r -eq 0 ]; then
    # Print the name of the output file (sans build root)
    if [ -z "$RPM_BUILD_ROOT" -o "$RPM_BUILD_ROOT" = "/" ]; then
        echo "$out"
    else
        echo "${out#$RPM_BUILD_ROOT}"
    fi
elif  [ $r -eq 124 ]; then
    # If the tool times out, ignore the issue
    echo >&2  "$lib: timed out parsing, skipping"
    r=0
fi
exit $r
