# Layout
# upstream has master, featureA, featureB
# upstream/master corresponds to upstream
# MAIN_REPO imports featureA,featureB from upstream

# main repo
cd /tmp
MAIN_REPO=/tmp/main-repo
rm -rf ${MAIN_REPO}
git init ${MAIN_REPO}
cd ${MAIN_REPO}
git commit --allow-empty -m "Initial commit."

# upstream
PROXY_REPOS=/tmp/proxy-repos
rm -rf ${PROXY_REPOS}
mkdir ${PROXY_REPOS}
git init ${PROXY_REPOS}/upstream
cd ${PROXY_REPOS}/upstream
echo "Created in upstream/master" > upstream.txt
git add .
git commit -m "Created in upstream/master"
git checkout -b featureA
echo "Created in upstream/featureA" > featureA.txt
git add .
git commit -m "Created in upstream/featureA"
git checkout master
git checkout -b featureB
echo "Created in upstream/featureB" > featureB.txt
git add .
git commit -m "Created in upstream/featureB"
git checkout master

# set up subtree merges, including local tracking branches for upstream
cd ${MAIN_REPO}
git remote add -f upstream ${PROXY_REPOS}/upstream/.git -t featureA -t featureB
git branch -t local_upstream_featureA upstream/featureA
git merge -s ours --no-commit local_upstream_featureA
git read-tree --prefix=featureA/ -u local_upstream_featureA
git commit -m "read tree upstream/featureA"
git branch -t local_upstream_featureB upstream/featureB
git merge -s ours --no-commit local_upstream_featureB
git read-tree --prefix=featureB/ -u local_upstream_featureB
git commit -m "read tree upstream/featureB"

# create in upstream repo, local to featureA
cd ${PROXY_REPOS}/upstream
git checkout featureA
echo "Created in upstream/featureA" > featureAonly.txt
git add .
git commit -m "Created in upstream/featureA - update"

# create in upstream repo, local to featureB
cd ${PROXY_REPOS}/upstream
git checkout featureB
echo "Created in upstream/featureB" > featureBonly.txt
git add .
git commit -m "Created in upstream/featureB - update"

# Modify common file in upstream for both branches
cd ${PROXY_REPOS}/upstream
git checkout master
echo "Modified common file in upstream/master" >> upstream.txt
git add .
git commit -m "Modified common file in upstream/master"

# Merge changes from master into featureA
cd ${PROXY_REPOS}/upstream
git checkout featureA
git merge master -m "Merged master into featureA"

# Merge changes from master into featureB
cd ${PROXY_REPOS}/upstream
git checkout featureB
git merge master -m "Merged master into featureB"

# pull upstream/featureA and upstream/featureB
cd ${MAIN_REPO}
git checkout master
# without --squash, order matters. Only the first pull applies the change to 
# featureX/upstream.txt. The second pull does not modify featureY/upstream.txt
# as it should.
git pull -s recursive -X subtree=featureA upstream featureA # --squash
git pull -s recursive -X subtree=featureB upstream featureB # --squash

