#!/usr/bin/env bash
#
# mfup
#
# Fetch and merge upstream changes, optionally with a branch
#

MFINFO=$(mfinfo) || exit

IFS=' ' read -a INFO <<< "$MFINFO"

ORG=${INFO[0]}
FORK=${INFO[1]}
REPO=${INFO[2]}
TARG=${INFO[3]}
OLDBRANCH=${INFO[4]}

case "$#" in
  0 ) BRANCH=$OLDBRANCH ;;
  1 ) BRANCH=$1 ;;
  * ) echo "Usage: `basename $0` [branch]" 1>&2 ; exit 1 ;;
esac

set -e

echo "Fetching upstream ($ORG/$REPO)..."
git fetch upstream

echo ; echo "Bringing $TARG up to date..."
git checkout -q $TARG || git branch checkout upstream/$TARG -b $TARG && git push --set-upstream origin $TARG
git merge upstream/$TARG
git push origin

if [[ $BRANCH != $TARG ]]; then
  echo ; echo "Rebasing $BRANCH on $TARG..."
  if git checkout $BRANCH; then
    echo
    if git rebase $TARG; then
      git push -f ; echo
      [[ $BRANCH != $OLDBRANCH ]] && git checkout $OLDBRANCH
    else
      echo "Looks like merge conflicts. Stopping here."
    fi
  else
    echo "No such branch!" ; echo
    git checkout $OLDBRANCH
  fi
fi
