#!/usr/bin/env bash

function verify_merge_ref {
  if git log --format='%s' -n 1 | grep -lq "$COMMIT_ID"; then
    return 0
  else
    return 1
  fi
}

function recreate_merge_ref {
  git checkout $COMMIT_ID
  git config user.name "CPE Teamcity"
  git config user.email "cpe-team@twitch.tv"
  if git merge --no-commit $PULL_REQUEST_TARGET -m "Merge branch $PULL_REQUEST_TARGET into $COMMIT_ID"; then
    echo "##teamcity[message text='Now working against recreated merge with $PULL_REQUEST_TARGET']"
  else
    echo "##teamcity[buildProblem description='Unable to recreate merge with $PULL_REQUEST_TARGET. Please check for merge conflicts.']"
  fi
}

git fetch origin +refs/pull/$PULL_REQUEST_NUMBER/merge:refs/pull/$PULL_REQUEST_NUMBER/merge
if git checkout refs/pull/$PULL_REQUEST_NUMBER/merge; then
  if verify_merge_ref; then
    echo "confirmed that $COMMIT_ID is in the merge ref"
    echo "##teamcity[message text='Now working against refs/pull/$PULL_REQUEST_NUMBER/merge']"
  else
    echo "current merge ref does not match $COMMIT_ID, recreating merge"
    recreate_merge_ref
  fi
else
  echo "##teamcity[buildProblem description='Unable to find refs/pull/$PULL_REQUEST_NUMBER/merge. Please check for merge conflicts.']"
fi
