#!/bin/sh
# Report whether upstream has tagged a release newer than the one this package
# is built from. Intended for a scheduled CI pipeline; see debian/uscan-ci.yml.
#
# Upstream tags releases on GitHub, so "is there something new" reduces to
# "does uscan find a tag above the version in debian/changelog".
set -eu

# --report does not download; --dehs gives machine-readable output.
uscan --report --dehs > uscan.dehs 2> uscan.log || true
[ -s uscan.log ] && cat uscan.log >&2

field() {
    sed -n "s|.*<$1>\\(.*\\)</$1>.*|\\1|p" uscan.dehs | head -1
}

have=$(field debian-uversion)
want=$(field upstream-version)

if [ -z "$want" ]; then
    echo "ERROR: uscan reported no upstream version; watch file or network broken" >&2
    cat uscan.dehs >&2
    exit 2
fi

echo "packaged upstream version: ${have:-unknown}"
echo "upstream now at:           $want"

if [ -n "$have" ] && dpkg --compare-versions "$want" gt "$have"; then
    cat >&2 <<MSG

Upstream has moved on. To update:

    gbp import-orig --uscan --no-interactive
    dch -v "$want-1" "New upstream release."

    # Then, in rough order of how often they actually change:
    #
    #  * diff the depends file. It is the authoritative list of what a build
    #    needs at runtime, and every entry in it is a Depends of this
    #    package, so a line added upstream is a missing dependency here:
    #        git diff \$PREV..upstream/latest -- depends
    #
    #  * check debian/patches still apply and are still needed. 0001 is a
    #    candidate for going away if upstream ever fixes the sbin PATH
    #    assumption itself.
    #
    #  * diff the top-level directory list against debian/*.install. A new
    #    top-level directory is silently dropped otherwise, and nothing
    #    fails until someone uses the layer that needs it:
    #        git diff --stat \$PREV..upstream/latest -- . | tail
    #
    #  * look for new prebuilt binaries that cannot be shipped:
    #        git diff --stat \$PREV..upstream/latest | grep -Ei '\.(deb|so|a|bin|jar)\$'

    gbp buildpackage --git-builder=sbuild

MSG
    exit 1
fi

echo "up to date"
