#!/bin/sh

set -o errexit
set -o nounset

PROJECT_ROOT=`pwd .`
export EMAIL=robot-webmaster@yandex-team.ru
PACKAGING_TOOLS="${PROJECT_ROOT}/packaging-tools"
DEBUILD_CMD="${PACKAGING_TOOLS}/bin/application_package.py"
DEBCLEAN_CMD="debclean"

if ls ${PROJECT_ROOT}/*.deb 1> /dev/null 2>&1
then
    rm ${PROJECT_ROOT}/*.deb
fi

if [ -z "$1" ]; then
    echo 'Not enough command line arguments - project name not specified'
    exit 1
fi

if [ -z "$2" ]; then
    echo 'Not enough command line arguments - branch name not specified'
    exit 1
fi

PROJECT_NAME="$1"
BRANCH_NAME="$2"

PROJECT_DIR="${PROJECT_ROOT}/$PROJECT_NAME/"

if [ ! -e "${PROJECT_DIR}/debian/changelog" ]; then
    echo 'debian/changelog not found in ${PROJECT_DIR}'
    exit 2
fi

if [ -e "${PACKAGING_TOOLS}" ]; then
    rm -Rf "${PACKAGING_TOOLS}"
fi
svn checkout svn+ssh://arcadia.yandex.ru/arc/trunk/arcadia/wmconsole/backend/packaging-tools

#Build phase
echo "Build debian package..."
cd $PROJECT_DIR
NEWVERSION=$(dpkg-parsechangelog | sed -ne 's/^Version: \(.*\)$/\1/p')+$BRANCH_NAME
dch -v $NEWVERSION "Feature branch $BRANCH_NAME" || exit 3

hg log -b $BRANCH_NAME -l30 | sed -ne 's/^summary:\s\s*\(.*\)$/\1/p' | while read line ; do
  dch -a "$line"
done || exit 3

cd $PROJECT_ROOT && $DEBUILD_CMD $1 || exit 4

echo "Debian clean..."
cd $PROJECT_DIR && $DEBCLEAN_CMD || exit 5
