#!/bin/bash
#
# Merges branch 1 into branch 2 in the super-rpeo and all submodules, recursively.
# branch1 and branch2 are the first and second command line arguments. 
# branch 2 will be left checked out after the merge.
#
# NCS, Nov 2017

[ -z "$1" ] && { echo "ERROR: You MUST provide the source and target branches" ; exit 1 ; }
[ -z "$2" ] && { echo "ERROR: You MUST provide the source and target branches" ; exit 1 ; }

echo "Merging branch $1 into branch $2"

# Verify that we are in the super-repo
[ -d CanAM ] ||  { echo "ERROR: You MUST be in the CanESM super-repo" ; exit 1 ; }

# Checkout the target branch
git checkout $2 ||  git checkout -b $2 || { echo "ERROR: could not checkout branch $2 in the super-repo" ; exit 1 ; }
git submodule update --recursive --checkout # At least start in a consistent place with the super repo
                                            # This protects from inheriting from a stray branch
                                            # which might have been checked out, but was not intended
                                            # to be the origin point for the merge.
git submodule foreach --recursive "git checkout $2 || git checkout -b $2" 

# Merge in the source branch
git merge $1 || { echo "WARNING: Problem in merging the super-repo" ; }
git submodule foreach --recursive "git merge $1 || :"

# Update submodule refs
git add CanAM CanCPL CanDIAG CanNEMO CCCma_tools
 
