#!/bin/sh

# Copyright 2012, gregor herrmann <gregoa@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

CDBS=0
DEBUG=0

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

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

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
        c)
            CDBS=1
            ;;
        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
    cd $PKG || continue
    dh_testdir || skip "$PKG doesn't look like a debian package."
    if [ "$CDBS" = "1" ] ; then
        grep -q cdbs debian/control && skip "Skipping CBDS package $PKG."
    fi

    echo "Working on $PKG…"

    # 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

Git-Dch: Ignore
EOL
    fi


    cd ..
done

echo "
Done.

How about reviewing and pushing your changes?

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

ssh git.debian.org 'touch /home/groups/pkg-perl/KGB-notifications-disabled' && \
mr -j4 push ; \
ssh git.debian.org 'rm /home/groups/pkg-perl/KGB-notifications-disabled'
"
