#!/usr/bin/env sh

GIT_REPO=$1

# Assert whether the path to the git repo is valid
if ! [ -d ${GIT_REPO}/.git ] ; then
    echo "Path specified: \"${GIT_REPO}\" is not a git repository root"
    exit 1
fi

# Switch to the root of the repository
cd ${GIT_REPO}

# Checkout the master branch
git checkout master

# Assert whether the current branch is master
if [ "$(git rev-parse --abbrev-ref HEAD)" != "master" ] ; then
    echo "Failed to switch to master branch"
    exit 1
fi

# Reset master to origin/HEAD
git reset --hard origin/HEAD

# Get the list of branches other than master
BRANCHES=$(git branch | grep -v master)

for BRANCH in ${BRANCHES} ; do
    
    # Merge the branch into master
    echo "Merging branch ${BRANCH}..."
    echo :wq | git merge ${BRANCH}
done
