#!/bin/sh

# Copyright 2012-2019, gregor herrmann <gregoa@debian.org>
# Copyright 2014, Salvatore Bonaccorso <carnil@debian.org>
# Released under the same terms as Perl

# INSTRUCTIONS:
# * to be run at the top of the packages direcory
# * adjust the actual changes / commit messages below,
#   marked as ADJUSTME

set -eu

DEBUG=0

usage() {
    echo "Usage:"
    echo "  $(basename $0) {-c|-d|-h}"
    echo
    echo "  Parameters:"
    echo "  -h    help"
    echo "  -d    debug / dry-run"
    exit 0
}

skip() {
    echo >&2 "$1"
    cd ..
}

run() {
    if [ "$DEBUG" = "1" ] ; then
        echo "D: $@"
    else
        $@
    fi
}

commit() {
    FILE=$(mktemp)
    cat > $FILE
    git commit --all --file=$FILE
    rm $FILE
}

warn() {
    echo >&2 "W: $1"
}

die() {
    echo >&2 "E: $1"
    exit 1
}

while getopts cdh OPT; do
    case "$OPT" in
        d)
            DEBUG=1
            ;;
        h)
            usage
            ;;
        *)
            die "Unknown parameter. Run $(basename $0) -h."
            ;;
    esac
done
shift $(($OPTIND - 1))

for PKG in $(ls -1d */ | sed -e 's:/$::') ; do
    echo "Working on $PKG …"

    cd $PKG     || continue
    dh_testdir  || { skip "$PKG doesn't look like a debian package."; continue; }
    [ -d .git ] || { skip "No .git directory in $PKG."; continue; }
    git checkout master

    # start real work
    # ADJUSTME start
    run cme fix dpkg -from control -filter Depends || true
    MSG="debian/control: update {versioned,alternative} (build) dependencies."
    # ADJUSTME end

    # commit it + changelog entry
    if git commit --dry-run -a > /dev/null ; then
        run commit <<EOL
$MSG
EOL

        run dch --no-auto-nmu --mainttrailer --release-heuristic=changelog "$MSG"
        run commit <<EOL
update changelog

Gbp-Dch: Ignore
EOL
    fi


    cd ..
done

echo "
Done.

How about reviewing and pushing your changes?

mr --stats diff --color=always origin/master | less -RS

dpt salsa kgb --all --off && \
mr -j4 -s push -o ci.skip origin master; \
dpt salsa kgb --all --on
"
