#!/bin/bash
#
# deliver tool
#
# script for making life easier when working with branches
# hierarchy. automaticaly rebases current branch and tries
# to build it. if it succeds it pushes changes to parrent
# branch.
#

SCRIPT_NAME="`basename "$0"`"
#LOG_FILE="`mktemp`"

function has_changes
{
  bzr status --short 2>&1 | grep -q -v '^?'
}

function has_notversioned
{
  bzr status --short 2>&1 | grep -q '^?'
}

# sanity check
if [ "`bzr root`" != "`readlink -f .`" ]
then
  echo "$SCRIPT_NAME: this script must be run from branch root directory (`bzr root`)" >&2
  exit 1
fi
if has_changes
then
  echo "$SCRIPT_NAME: error: pending changes have been found" >&2
  exit 2
fi
if has_notversioned
then
  echo "$SCRIPT_NAME: error: not versioned files have been found - either add them to repository or ignore list" >&2
  exit 2
fi
#if ! [ -f "$LOG_FILE" ]
#then
#  echo "$SCRIPT_NAME: unable to create log file" >&2
#  exit 3
#fi

# read configuration
. ./bzr_team.conf  || exit $?
. ./bzr_build.conf || exit $?

bzr update > /dev/null 2>&1 || exit $?

# perform rebase
echo "$SCRIPT_NAME: rebasing branch"
./rebase || exit $?

# try building project
echo "$SCRIPT_NAME: building project"
if build_project
then
  # do final commit/revert
  echo "$SCRIPT_NAME: delivering"
  bzr push "$PARENT"
  RET=0
else
  echo "$SCRIPT_NAME: build failed - leaving changes for further inspections" >&2
  echo "$SCRIPT_NAME: note: to rollback rebase type 'bzr revert'"             >&2
  RET=10
fi

exit $RET
