#!/bin/sh
set -e

PATCH_BRANCH="${PATCH_BRANCH:-patch-queue}"
GBP_CONF="${GBP_CONF:-debian/gbp.conf}"

if [ -z "$MASTER_BRANCH" ]; then
    if [ -f "$GBP_CONF" ]; then
        MASTER_BRANCH=`awk -F' *= *' '/debian-branch/{print $2}' "$GBP_CONF"`
    fi
    MASTER_BRANCH="${MASTER_BRANCH:-master}"
fi

if [ -z "$UPSTREAM_BRANCH" ]; then
    if [ -f "$GBP_CONF" ]; then
        UPSTREAM_BRANCH=`awk -F' *= *' '/upstream-branch/{print $2}' "$GBP_CONF"`
    fi
    UPSTREAM_BRANCH="${UPSTREAM_BRANCH:-upstream}"
fi

echo "Debian branch is $MASTER_BRANCH"
echo "Upstream branch is $UPSTREAM_BRANCH"

error () {
    echo "E: $1"
    exit 1
}

if [ -n "`git branch | grep $PATCH_BRANCH`" ]; then
    error "There is already a branch $PATCH_BRANCH"
else
    git checkout -b "$PATCH_BRANCH" "$UPSTREAM_BRANCH"

    ## When $MASTER_BRANCH:debian/patches/series doesn't exist, git cat-file
    ## will produce an empty output (along with an error on stderr).
    for patch in `git cat-file -p "$MASTER_BRANCH":debian/patches/series 2>/dev/null`; do
	git cat-file -p "$MASTER_BRANCH":debian/patches/$patch | git am;
    done
fi
