#!/bin/bash

set -e # bail on errors

function current_branch() {
  git rev-parse --abbrev-ref HEAD | sed -e 's/^heads\///'
}

ORIG_BRANCH=$(current_branch)
DEFAULT_REMOTE=$(git config --get branch.master.remote)
REMOTE="${1:-$DEFAULT_REMOTE}"
if [[ "$ORIG_BRANCH" = "HEAD" ]]; then
  echo "Cannot update in a detached HEAD state"
  exit 1
fi
if [[ -z "$2" ]]; then
  BRANCHES="$ORIG_BRANCH"
else
  if [[ "$1" = "$REMOTE" ]]; then
    shift
  fi
  BRANCHES="$@"
fi

STASH_OUTPUT=$(git stash)
if [[ "$STASH_OUTPUT" = "No local changes to save" ]]; then
    POP_STASH=0
else
    POP_STASH=1
fi

git fetch --prune --tags "$REMOTE"

for BRANCH in $BRANCHES; do
  echo "* Updating $BRANCH from $REMOTE/$BRANCH"
  if [[ "$BRANCH" != "$(current_branch)" ]]; then
    git checkout "$BRANCH"
  fi
  git rebase "$REMOTE/$BRANCH"
done

if [[ "$ORIG_BRANCH" != "$(current_branch)" ]]; then
  git checkout "$ORIG_BRANCH"
fi

if [[ $POP_STASH -eq 1 ]]; then
  git stash pop
fi
