#!/bin/sh
set -eu

if [ $# -ne 1 ]; then
  echo "Usage: $(basename "$0") <branch>" >&2
  exit 2
fi

branch="$1"
base_remote="upstream"
base_branch="master"
base_ref="$base_remote/$base_branch"

# avoid rebasing with a dirty tree
if ! git diff --quiet || ! git diff --cached --quiet; then
  echo "Working tree has uncommitted changes; commit/stash first." >&2
  exit 2
fi

git fetch "$base_remote" "$base_branch"

if git show-ref --verify --quiet "refs/heads/$branch"; then
  git checkout "$branch"
  git rebase "$base_ref"
else
  git checkout -b "$branch" "$base_ref"
fi
