#!/bin/sh
# Rebases amq-maas with changes from origin/master

set -e

PUSH_FORCE_FLAG="--force-with-lease"   # Available in git 1.8.5 and beyond
DATE=$(date --utc --iso-8601=seconds)
TAG=auto_rebase_$(cat /proc/sys/kernel/random/uuid)
CURR_BRANCH=$(git rev-parse --abbrev-ref HEAD)

if ! git push -? 2>&1 | grep --quiet -- '--force-with-lease';
then
    PUSH_FORCE_FLAG="--force"
fi

function restore_curr_branch {
    git checkout ${CURR_BRANCH}
}
trap restore_curr_branch EXIT

git config --global user.email "amq-online-ci@redhat.com"
git config --global user.name "AMQ Online CI"

git fetch origin
git checkout amq-maas
git reset --hard FETCH_HEAD
git tag --annotate --message="Auto rebase from master to amq-maas ${DATE}" ${TAG}
# git-rebase will fail if merge is required
git rebase origin/master amq-maas

STAT=$(git status --short  --branch | head -1)

if [[ "${STAT}" =~ ^.*ahead.*$ ]]
then
    echo "Changes found, pushing tag for original tree"
    git push origin ${TAG}
    git commit --allow-empty --m "Auto rebase from master, previous tree tagged: ${TAG}"
    git push ${PUSH_FORCE_FLAG} --verbose origin amq-maas
else
    echo "No changes found to rebase from master"
fi



