#!/bin/sh

usage() {
    cat <<END >&2
Usage: $0 -- merge to Debian branch
 -a         use the most recent tag. Default: only consider a tag on HEAD
 -d BRANCH  Branch name (default: 'deb' or 'debian')
 -e         edit before committing the merge
 -h         print this help text and exit
 -o ORIGIN  Use this remote instead of "intern"; '-' to disable
 -p         Do NOT try to push Python packages to pypi
 -s DIST    Use "sbu -d DIST" instead of 'debch' to build
 -t VERS    Behave as if this tag was on HEAD
END
}

TEMP=$(getopt -o 'aed:ho:ps:t:' -n "$(basename "$0")" -- "$@")
if [ $? -ne 0 ]; then
        echo 'Terminating...' >&2
        exit 1
fi
eval set -- "$TEMP"
unset TEMP

T=
TT=n
ED=n
DEB=
SBU=
PYPI=y
VERS=
ORIG=intern
while true ; do
    case "$1" in
        '-a')
            TT=y
            shift ;;
        '-d')
            DEB="$2"
            shift 2 ;;
        '-o')
            ORIG="$2"
            shift 2 ;;
        '-e')
            ED=y
            shift ;;
        '-h')
            usage
            ;;
        '-p')
            PYPI=n
            shift ;;
        '-s')
            SBU="$2"
            shift 2 ;;
        '-t')
            T="$2"
            shift 2 ;;
        '--')
            break ;;
        *)
            echo "Unknown argument '$1'" >&2
            exit 1
    esac
done

test "x$ORIG" = "x-" || git fetch "$ORIG"

set -ex
if test -n "$T" ; then
    :
elif test "$TT" = "y" ; then
    T=$(git describe --tags | sed -e 's/-.*//')
else
    T=$(git describe --tags --exact-match)
fi
TT=$(echo $T | sed -e 's/^[a-z]*//')

test "x$ORIG" = "x-" || git pull "$ORIG"

if test -n "$DEB" ; then
    git describe "$DEB" >/dev/null
elif git describe --all deb >/dev/null 2>&1; then
    DEB=deb
elif git describe --all debian >/dev/null 2>&1; then
    DEB=debian
elif git describe --all intern/deb >/dev/null 2>&1; then
    DEB=deb
elif git describe --all intern/debian >/dev/null 2>&1; then
    DEB=debian
else
    echo "Neither 'deb' nor 'debian' branches found." >&2
    exit 1
fi

B="$(git rev-parse --abbrev-ref HEAD)"
if test -z "$B" ; then
    echo "You're on a detached head. Exiting."
    exit 1
fi
if test "$B" = "$DEB" ; then
    echo "You can't be on the '$DEB' branch when you do this." >&2
    exit 1
fi

git switch "$DEB"
test "x$ORIG" = "x-" || git merge "$ORIG" "$DEB"
git merge --no-commit "$B"

D=$(dpkg-parsechangelog -S distribution)
if dpkg-parsechangelog -S version | grep -qs -- - ; then V="-1" ; else V=".1"; fi
debchange --distribution $D --force-distribution -v "$TT$V" "Merge"
git add debian/changelog
if test $ED = y ; then
    echo "Edit some stuff, then 'exit'"
    bash
fi
git commit -a -m "Merge to $T"
if test -n "$SBU" ; then
    sbu -d $SBU
else
    debch
fi
git switch "$B"
if test $PYPI = "y" ; then
    if test -s setup.py || test -s pyproject.toml ; then
        make pypi
    fi
fi
