#!/bin/sh
# Copyright 2011 Simon Cross <hodgestar@gmail.com>
# GPL - see COPYING for details

SIGNER=$1
if [ "x$SIGNER" = "x" ] ; then
    echo "Usage: sutekh-makedeb <signer> [<build-counter>]"
    echo "  * Signer is the name and email address of the package signer."
    echo "    It is also used to select the key to sign with."
    echo "  * The optional build-counter determines the Debian-Version."
    echo "    The Debian-Version is <build-counter>~<suite name>."
    echo "    The default build counter is 1. Increment it if you need"
    echo "    to create new deb builds of the same Sutekh release."
    exit 1
fi

BUILD_COUNTER=$2
if [ "x$BUILD_COUNTER" = "x" ] ; then
    BUILD_COUNTER="1"
fi

SUITES="saucy raring quantal precise"
SUTEKH_VERSION=`PYTHONPATH=. python -c "from sutekh import SutekhInfo; print SutekhInfo.SutekhInfo.VERSION_STR"`
DEB_VERSION=`echo "$SUTEKH_VERSION" | sed -e "s/\(rc\|a\|b\)/~\1/"`
SDIST_FILE="dist/Sutekh-${SUTEKH_VERSION}.orig.tar.gz"
DEBPATCH_FOLDER="deb-patches"

if [ ! -e "$SDIST_FILE" ] ; then
    echo "Please copy the source tarball for this release to $SDIST_FILE."
    echo "NB: Do not simply re-build the source tarball -- it should be"
    echo "    the same source tarball uploaded to sourceforge (for sanity)"
    echo "    and used in any previous uploads to Launchpad's build system"
    echo "    (or Launchpad will reject your package)."
    exit 1
fi


make_deb () {

    SUITE=$1
    EXTRA_CFG="deb_dist/sutekh-$SUITE.cfg"

    # make extra config file
    touch "$EXTRA_CFG"
    echo "[Sutekh]" >> $EXTRA_CFG
    echo "Debian-Version: $BUILD_COUNTER~$SUITE" >> $EXTRA_CFG
    echo "Forced-Upstream-Version: $DEB_VERSION" >> $EXTRA_CFG

    PATCHFILE=""
    if [ -f "$DEBPATCH_FOLDER/$SUITE.diff" ]; then
       # Add suite-specific patch file to the extra config file
       cp "$DEBPATCH_FOLDER/$SUITE.diff" deb_dist
       PATCHFILE="-p deb_dist/$SUITE.diff"
    elif [ -f "$DEBPATCH_FOLDER/makedeb.diff" ]; then
       # Add general patch file if it exists
       cp "$DEBPATCH_FOLDER/makedeb.diff" deb_dist
       PATCHFILE="-p deb_dist/makedeb.diff"
    fi

    # build source tarball and .dsc
    py2dsc -z "$SUITE" -x "$EXTRA_CFG" $PATCHFILE "$SDIST_FILE"

    # build .changes file (see https://github.com/astraw/stdeb/issues/37)
    cd deb_dist/sutekh-${DEB_VERSION}
    # We pass auto-commit through to dpkg-source, so it doesn't complain about
    # any changes we've made via the py2dsc patch
    debuild -S -e"$SIGNER" --source-option=--auto-commit
    cd ../..

}

# santize environment
rm -rf deb_dist
mkdir deb_dist

# build Debian source package for each suite
for suite in $SUITES ; do
    echo "================================="
    echo "Making .deb for: $suite"
    echo "================================="
    make_deb $suite
done

# don't upload for now
echo "================================="
echo "Now do:"
echo " dput ppa:sutekh/ppa <source.changes>"
