#!/bin/sh

set -o errexit
set -o nounset

PROJECT_ROOT=`pwd .`
export CONDUCTOR_OAUTH=`cat ${HOME}/.conductor_oauth`
export EMAIL=robot-webmaster@yandex-team.ru
export SVN_SSH="ssh -v -i /home/robot-webmaster/.ssh/id_rsa"
export _JAVA_OPTIONS="-Djava.net.preferIPv6Addresses=True -Djava.net.preferIPv4Stack=False"
PACKAGING_TOOLS="${PROJECT_ROOT}/packaging-tools"
DEBUILD_CMD="dpkg-buildpackage -rfakeroot -sa -e${EMAIL} -b"
COMPILE_CMD="${PACKAGING_TOOLS}/bin/application_package.py"
DEBCLEAN_CMD="debclean"
REPO_NAME="search-rcss-common"
DEBRELEASE_CMD="debrelease --to ${REPO_NAME} --nomail"
DEBTICKET_CMD="debticket -n --branch unstable --oauth ${CONDUCTOR_OAUTH}"


if [ -z "$1" ]; then
    echo 'Not enough command line arguments - project name not specified'
    exit 1
fi
PROJECT_DIR="${PROJECT_ROOT}/$1/"

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://robot-webmaster@arcadia.yandex.ru/arc/trunk/arcadia/wmconsole/backend/packaging-tools

#Build phase
echo "Compiling sources"
cd $PROJECT_ROOT && $COMPILE_CMD $1 || exit 3

echo "Build debian package..." 
cd $PROJECT_DIR && $DEBUILD_CMD || exit 3

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

#Deploy phase
DEB_SOURCE=$(dpkg-parsechangelog | sed -n 's/^Source: //p')
DEB_VERSION=$(dpkg-parsechangelog | sed -n 's/^Version: //p')

PACKAGES_IN_REPO=$(ssh -i /home/robot-webmaster/.ssh/id_rsa robot-webmaster@search-rcss-common.dupload.dist.yandex.ru "find_package.sh '${DEB_SOURCE}=${DEB_VERSION}' 2> /dev/null | fgrep ${DEB_SOURCE} | wc -l")

PACKAGE_ID=${DEB_SOURCE}-${DEB_VERSION}

echo "Deploy package..."
if [ "${PACKAGES_IN_REPO}" = "0" ]; then
    echo "Release package to ${REPO_NAME}..." 
    cd $PROJECT_DIR && $DEBRELEASE_CMD && $DEBTICKET_CMD || exit 5
    echo "[DEBUG] CONDUCTOR_OAUTH=${CONDUCTOR_OAUTH}"

    #echo "Marking source code with tag ${PACKAGE_ID}..."
    #hg bookmark "${PACKAGE_ID}" || exit 6
    # push should always return false, because no actual changes pushed
    #hg push -B "${PACKAGE_ID}" && exit 7 || exit 0
else
    echo "Package ${PACKAGE_ID} is already in ${REPO_NAME} repo. Conductor ticket will not be created."
    echo "[DEBUG] PACKAGES_IN_REPO=${PACKAGES_IN_REPO}"
fi
