#!/bin/bash

set -e

# Git wrapper that will create a pull request just for the set of files listed,
# but doesn't change the current working set.

if [[ $# -lt 3 ]]; then
  echo "Usage: create_pull.sh [BRANCH] [MESSAGE] [FILES...]"
  exit 1
fi

NEW_BRANCH="$1"
MESSAGE="$2"
ORIG_BRANCH=$(git symbolic-ref --short HEAD)

if [[ "${NEW_BRANCH}" == "${ORIG_BRANCH}" ]]; then
  echo "New branch is the same as the existing branch?"
  exit 1
fi

# Make sure that all the files listed are committed.
git commit --allow-empty -m "${MESSAGE}" ${*:3}

# Save the current working tree.
git stash save

# Create a new branch from master.
git checkout master
git checkout -B "${NEW_BRANCH}"

# Checkout and commit the desired changes.
git checkout "${ORIG_BRANCH}" ${*:3}
git commit -m "${MESSAGE}" -a

# Push to the remote.
git push origin "${NEW_BRANCH}"

# Go back to the original branch.
git checkout "${ORIG_BRANCH}"

# Restore the working directory.
git stash pop

echo "*** Visit https://git.zooxlabs.com/zooxco/driving/compare/${NEW_BRANCH}?expand=1"
