#!/bin/sh -e
BUILDDIR=`dirname $PWD`
EXTRAPBUILDER=/var/cache/pbuilder/extra

cat > ~/.pbuilderrc <<EOT
# helps on sebio03 and does no harm otherwise
# see https://pbuilder.alioth.debian.org/#tmpdir
export TMPDIR=/tmp
AUTO_DEBSIGN=yes
PKGNAME_LOGFILE=yes
BUILDRESULT=$BUILDDIR
# BUILDRESULT=$BUILDDIR
# HOOKDIR=/home/tillea/.pbuilder -- it's actually /var/cache/pbuilder/hooks
# BINDMOUNTS="/home/vagrant/_pbuilder_local_deps /dev/shm"
# This is a workaround a problem that /dev/shm is not mounted in pbuilder chroot
# BINDMOUNTS="/dev/shm" - set in /etc/pbuilderrc
EXTRAPACKAGES="apt-utils"
EOT

if [ `dpkg-parsechangelog | awk '/^Distribution:/ {print $2}'` = trusty ] ; then
    echo "This is a targeting at Debian Med PPA"
    STABLEVERSION=""
else
  if dpkg-parsechangelog | awk '/^Version:/ {print $2}' | grep -q '~bpo' ; then
    echo "This is a backport"
    # enable local packages in pbuilder
    if [ -d $EXTRAPBUILDER ] ; then
      rm -rf $EXTRAPBUILDER/release
      ln -s jessie $EXTRAPBUILDER/release
    fi
cat >> ~/.pbuilderrc <<EOT
OTHERMIRROR="deb [trusted=yes] file:///var/cache/pbuilder/extra/jessie ./"
BASEPATH="/var/cache/pbuilder/jessie-base.cow"
EOT
    STABLEVERSION=`grep '~bpo' debian/changelog | head -n2 | tail -n1 | sed 's/^[^ ]\+ (\([0-9].*-[.0-9]\+~bpo[0-9+]\+\)) .*-backports; urgency=.*$/\1/'`
    # versions of backports of Debian native packages (like dh-r) do not necessarily contain a - sign
    if echo $STABLEVERSION | grep -- '-backports' ; then
      # may be this also works in general ...
      STABLEVERSION=`grep '~bpo' debian/changelog | head -n2 | tail -n1 | sed 's/^[^ ]\+ (\([.0-9~]\+~bpo[0-9+]\+\)) .*-backports; urgency=.*$/\1/'`
    fi
    STABLEVERSION="-v$STABLEVERSION"
  else
    echo "Make sure we use sid config"
    # enable local packages in pbuilder
    if [ -d $EXTRAPBUILDER ] ; then
      rm -rf $EXTRAPBUILDER/release
      ln -s sid $EXTRAPBUILDER/release
    fi
cat >> ~/.pbuilderrc <<EOT
OTHERMIRROR="deb [trusted=yes] file:///var/cache/pbuilder/extra/sid ./"
EOT
    STABLEVERSION=""
  fi
fi


# Aufruf für binary-only build:
#   pdebuild --debbuildopts "-B"
/usr/bin/pdebuild --pbuilder cowbuilder --debbuildopts "$STABLEVERSION" --debsign-k "Andreas Tille <tille@debian.org>"  # $@
pkg=`dpkg-parsechangelog | awk '/^Source:/ {print $2}'`
version=`dpkg-parsechangelog | awk '/^Version:/ {print $2}' | sed -e 's/^[0-9]*://' -e 's/-.*//'`
rm -f debian/files
cd ..
lintian -i ${pkg}_${version}*[46l].changes
