#!/usr/bin/env bash

set -u -e -o pipefail

BASEDIR=$(dirname "$0")

if [ $# -eq 0 ]; then
    echo "Rebase github PR onto a branch"
    echo
    echo "$0 branch_to_rebase_on PR_NUMBER"
    echo
    exit 0
fi

REBASE_ON="$1"
PR_NO="$2"


HEAD_LABEL=`curl -s https://api.github.com/repos/angular/angular/pulls/$PR_NO | node $BASEDIR/utils/json_extract.js head.label`
echo $HEAD_LABEL
IFS=':' read -r -a array <<< "$HEAD_LABEL"
USER="${array[0]}"
USER_GIT_URL="git@github.com:$USER/angular.git"
BRANCH="${array[1]}"
OLD_BRANCH=`git branch | grep \* | cut -d ' ' -f2`

echo =====================================================
echo Rebasing $USER_GIT_URL branch $BRANCH onto $REBASE_ON
echo =====================================================

git fetch $USER_GIT_URL $BRANCH
git co FETCH_HEAD
PUSH_CMD="git push $USER_GIT_URL HEAD:$BRANCH -f";
RESTORE_CMD="git co $OLD_BRANCH"
git rebase upstream/master
if [ $? -eq 0 ]; then
    $PUSH_CMD
    $RESTORE_CMD
else
    echo ===========================
    echo Git rebase failed. RECOVER WITH:
    echo "       $PUSH_CMD"
    echo "       $RESTORE_CMD"
    echo ===========================
fi
