#!/bin/sh

set -u -e -o pipefail

BASEDIR=$(dirname "$0")
BASEDIR=`(cd $BASEDIR; pwd)`

if [ $# -eq 0 ]; then
  echo "Merge github PR into the current branch"
  echo
  echo "$0 PR_NUMBER"
  echo
  exit 0
fi

PR_NUMBER="$1"
CURRENT_BRANCH=`git rev-parse --abbrev-ref HEAD`
PR_SHA_COUNT=`curl -s https://api.github.com/repos/angular/angular/pulls/$PR_NUMBER | node $BASEDIR/utils/json_extract.js commits`
PR_LABELS=`curl -s https://api.github.com/repos/angular/angular/issues/$PR_NUMBER/labels`
PR_ACTION=`echo "$PR_LABELS" | node $BASEDIR/utils/json_extract.js "name=^PR action:"`
PR_TARGET=`echo "$PR_LABELS"  | node $BASEDIR/utils/json_extract.js "name=^PR target:"`
PR_CLA=`echo "$PR_LABELS"  | node $BASEDIR/utils/json_extract.js "name=^cla"`
MASTER_BRANCH='master'
SHA=`git rev-parse HEAD`
PATCH_BRANCH=`git branch --list '*.x' | cut -d ' ' -f2- | sort -r | head -n1`
# Trim whitespace
PATCH_BRANCH=`echo $PATCH_BRANCH`

if [[ "$PR_ACTION" != "PR action: merge" ]]; then
  echo The PR is missing 'PR action: merge' label, found: $PR_ACTION
  exit 1
fi

if [[ "$PR_CLA" != "cla: yes" ]]; then
  echo The PR is missing 'cla: Yes' label, found: $PR_CLA
  exit 1
fi


if [[ $PR_TARGET == "PR target: master & patch" ]]; then
  MERGE_MASTER=1
  MERGE_PATCH=1
elif [[ $PR_TARGET == "PR target: master-only" ]]; then
  MERGE_MASTER=1
  MERGE_PATCH=0
elif [[ $PR_TARGET == "PR target: patch-only" ]]; then
  MERGE_MASTER=0
  MERGE_PATCH=1
else
  echo "Unknown PR target format: $PR_TARGET"
  exit 1;
fi

if [[ $CURRENT_BRANCH == $MASTER_BRANCH ]]; then
  if [[ $MERGE_MASTER == 0 ]]; then
    echo "This PR is not intended for master branch: $PR_TARGET"
    exit 1
  fi
elif [[ $CURRENT_BRANCH == $PATCH_BRANCH ]]; then
  if [[ $MERGE_PATCH == 0 ]]; then
    echo "This PR is not intended for patch branch: $PR_TARGET"
    exit 1
  fi
else
  echo "Current branch $CURRENT_BRANCH does not match $MASTER_BRANCH or $PATCH_BRANCH."
  exit 1
fi


CHERRY_PICK_PR="git cherry-pick upstream/pr/$PR_NUMBER~$PR_SHA_COUNT..upstream/pr/$PR_NUMBER"
REWRITE_MESSAGE="git filter-branch -f --msg-filter \"$BASEDIR/utils/github_closes.js $PR_NUMBER\" HEAD~$PR_SHA_COUNT..HEAD"

echo "======================"
echo "GitHub Merge PR Steps"
echo "======================"
echo "   $CHERRY_PICK_PR"
echo "   $REWRITE_MESSAGE"
echo "----------------------"

echo ">>> Cherry Pick: $CHERRY_PICK_PR"
$CHERRY_PICK_PR

echo
echo ">>> Rewrite Messages: $REWRITE_MESSAGE"
# Next line should work, but it errors, hence copy paste the command.
# $REWRITE_MESSAGE
git filter-branch -f --msg-filter "$BASEDIR/utils/github_closes.js $PR_NUMBER" HEAD~$PR_SHA_COUNT..HEAD

echo
echo ">>>>>> SUCCESS <<<<<<"