#!/usr/bin/zsh -feu

set -x
CHANGESFILE=$1

# Format of *.changes:

# Version: 2:21.1.7-3-maruska
# Distribution: unstable
# how to convert to SID?
# Source: xorg-server

extract()
{
    local KEYWORD=$1
    sed -n -e "s/^$KEYWORD: \(.*\)$/\1/p" $CHANGESFILE
}

usage()
{
    cat <<EOF
usage: ${0##*/} [+-h} [--] package-version.changes

Given a debian changes file from a build, assuming
it has been processed in the reprepro installation,
update the Git repository of the reprepro.
EOF
}

while getopts :h OPT; do
    case $OPT in
        h|+h)
            usage
            exit 0
            ;;
        *)
            usage >&2
            exit 2
    esac
done
shift OPTIND-1
OPTIND=1

source=$(extract Source)
version=$(extract Version)
distro=$(extract Distribution)

if [[ $distro = unstable ]];
then
    distro=sid
fi

REPREPRO_DIR=$REPREPRO_BASE_DIR

# go into the GIT:
(
    cd $REPREPRO_DIR
    # todo: Ensure nothing is staged
    # if the package == Source then Source field is NOT present in the *.deb !
    reprepro --list-format '${$fullfilename}\n' listfilter $distro "Source (% $source) | Package (% $source)" |\
        xargs git add
    # --verbose

    # todo: why Packages and Packages.gz ??
    git add --force dists/$distro

    # I need to stage all removed files!
    git add pool
    # git commit -m "drop old $source"


    # is anything scheduled?
    if ! git diff --cached --exit-code &> /dev/null
    then
        git commit -m "upgrade packages from $source to $version ($distro)"
    fi

    git --no-pager log --max-count=1 --compact-summary --stat

    sleep 1
    $REPREPRO_DIR/deploy
)
