#!/bin/sh

[ -n "$push_username" ] || exit 102
[ -n "$push_password" ] || exit 103
[ -n "$push_repo" ] || exit 104
HGMERGE=merge
export HGMERGE

rollback() {
  EXIT="$?"
  if [ -n "$BASETIP" ]; then
    echo "Script failed with exitcode $EXIT rolling back to $BASETIP"
    hg update -C
    hg --config extensions.mq= strip -n "$BASETIP"
    hg pull -r "$BASETIP"
  else
    echo "No rollback, exitcode $EXIT"
  fi
}

HEADS=`hg heads --template "{node}\n" | wc -l`
if [ $HEADS = 2 ]; then
    echo "2 heads, here is some diagnostic"
    echo hg heads:
    hg heads
    echo hg stat
    hg stat
    exit 1
fi
BASETIP=`hg id -i | tr -d "+"`
trap rollback EXIT

hg fetch -u "$push_username"@netbeans.org http://hg.netbeans.org/"$push_repo"
hg push https://"$push_username":"$push_password"@hg.netbeans.org/"$push_repo" || exit 9
unset BASETIP
exit 0
