#!/bin/sh

# shlibs-watchdog -- Break the build if any .shlibs file was not updated.
#
# Mainly useful for packages that are developed as a stack and thus do
# not support partial upgrades.

if [ -z "$1" ]; then
    echo "Error: You must specify the path to the debian/ directory." >&2
    exit 1
fi

changelogversion="$(dpkg-parsechangelog -l "$1"/changelog -S Version)"
ret=0

# iterate over Section: libs packages
for pkg in $(sed -n '/^\(Package\|Section\): /s@^\(Package\|Section\): @@p' "$1"/control|grep -B1 '^libs$'|grep -v '^libs'); do
    f="$1"/"$pkg".shlibs
    if [ ! -f "$f" ]; then
        echo "Error: library package $pkg is missing its shlibs file." >&2
        ret=1
        continue
    fi

    ncommas="$(tr -cd ',' < "$f"|wc -c)"
    for i in $(seq 0 $ncommas); do
        deppkg="$(cut -d ' ' -f3- "$f" |cut -d, -f$((i+1))|sed 's@^ @@'|cut -d' ' -f1)"
        if [ "$pkg" = "$deppkg" ]; then
            dpkg --compare-versions \
                 "$changelogversion" \
                 "$(cut -d ' ' -f3- "$f" |cut -d, -f$((i+1))|sed 's@^ @@'|cut -d'(' -f2|cut -d')' -f1|cut -d' ' -f1)" \
                 "$(cut -d ' ' -f3- "$f" |cut -d, -f$((i+1))|sed 's@^ @@'|cut -d'(' -f2|cut -d')' -f1|cut -d' ' -f2)"
            if [ $? -ne 0 ]; then
                echo "Error: $f was not updated for $changelogversion. Output follows." >&2
                grep -e^ -H "$f"
                ret=1
            fi
        fi
    done
done

exit $ret
