#!/bin/sh
# Copyright (©) 2021, Damyan Ivanov <dmn@debian.org>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of either:
#
# a) the GNU General Public License as published by the Free Software
#    Foundation; either version 1, or (at your option) any later
#    version, or
#
# b) the "Artistic License" which comes with Perl.


set -e -u

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

`dpt shell-lib`

[ -n "${DEBEMAIL:-}" ] || die "DEBEMAIL not set. Who are you?"

while [ -n "${1:-}" ]; do
    dpt co "$1"
    LATEST_VER=$(dpkg-parsechangelog -SVersion)
    echo "$LATEST_VER" | grep -q -- '-1$' || die "Latest version '$LATEST_VER' is not a -1 version"
    FIRST_VER=$(dpkg-parsechangelog --reverse -SVersion)
    [ "$FIRST_VER" = "$LATEST_VER" ] || die "Package is uploaded more than once"

    UPLOADERS=$(perl -ne'if (/^Uploaders:/) {print; while(<>) { print, next if /^\s/; exit 0}}' debian/control)
    [ -n "$UPLOADERS" ] || die "Unable to determine Uploaders"
    if echo "$UPLOADERS" | grep -q "$DEBEMAIL"; then
        dch -i "No-changes source-only upload to enable testing migration"
    else
        dch -i "Team upload"
        dch -a "No-changes source-only upload to enable testing migration"
    fi

    dch -r ''

    # build the package
    sb

    dpkg-parsechangelog

    # upload to the archive. uses the result of the build command above
    upload-debian

    debcommit -a -r

    dpt push

    shift
done
