#!/bin/sh
set -e

usage () {
    cat <<'EOF'
usage: git merges-cleanly [-vh] <branch>

Performes a temporal merge against the given branch (but aborts or undoes
the merge) and reports success or failure through the exit code.

Options:
-h    Show this help
-l    List conflicting files
EOF
}

showlist=0
while getopts lh flag; do
    case "$flag" in
        h) usage; exit 0;;
        l) showlist=1;;
    esac
done
shift $(($OPTIND - 1))

if [ $# -ne 1 ]; then
    usage >&2
    exit 2
fi

branch=$1

git sha -q "$1"

if git is-dirty -iw; then
  echo "Can't check when you have local changes." >&2
  exit 2
fi

if git merge --quiet "$branch" >/dev/null 2>/dev/null; then
  git undo-merge >/dev/null 2>/dev/null
  exit 0
else
  if [ $showlist -eq 1 ]; then
    git diff --name-only --diff-filter=U
  fi

  git merge --abort >/dev/null 2>/dev/null

  if [ $showlist -eq 1 ]; then
    exit 0
  else
    exit 1
  fi
fi
