#!/usr/bin/env bash

# This test helps to keep libnxz's ABI stability. It does the following checks:
#   1. Make sure that libnxz provides all zlib symbols
#   2. Guarantee that new symbols are not added/removed by mistake

# These should be either the .so files or their descriptions generated by abidw
zlib_abi_orig="${srcdir:+${srcdir}/}libz.abi"
libnxz_abi="${srcdir:+${srcdir}/}libnxz.abi"
libnxz="$1"
zlib_supp="${srcdir:+${srcdir}/}zlib.supp"

which abidiff &> /dev/null
if [ $? -ne 0 ]; then
    echo "No abidiff binary found, skipping..."
    exit 77
fi

# libabigail 2.0.0 started to use a new XML format that can't be compared with
# files generated using older versions, so skip if version is too old
abidiff_version="$(abidiff --version | cut -d' ' -f2)"
if [ $(echo $abidiff_version | cut -d'.' -f1) -lt 2 ]; then
    echo "Need libabigail version >= 2, found ${abidiff_version}. Skipping..."
    exit 77
fi

# Exit on first failure
set -e

if [ -z "${libnxz}" ]; then
    libnxz="../lib/.libs/libnxz.so"
fi

if [ ! -f "${libnxz}" ]; then
    echo "Couldn't find file: ${libnxz}"
    exit 1
fi

if [ ! -f "${zlib_abi_orig}" ] || [ ! -f "${libnxz_abi}" ]; then
    echo "Missing libz ABI file or .so!"
    exit 1
fi

# Currently abidiff does not allow to ignore SONAME changes, which means it will
# always spot changes when comparing libnxz and libz. To avoid this, let's
# artificially change libz's SONAME to suppress this error
zlib_abi="${zlib_abi_orig}.mod"
sed "s/soname='libz.so.1'/soname='libnxz.so.0'/g" ${zlib_abi_orig} > ${zlib_abi}
trap "rm -f ${zlib_abi}" EXIT

# We are only interested in the zlib symbols that should be here but aren't
echo "Checking missing zlib symbols..."
abidiff --suppressions "${zlib_supp}" --no-added-syms ${zlib_abi} ${libnxz}

echo "Checking changes on libnxz's ABI..."
abidiff ${libnxz_abi} ${libnxz}
