#!/bin/sh

# Creating project that will be used as subtree
mkdir sub_project
cd sub_project
git init
touch toto
echo "-----------------" >> toto
echo "- toto file">> toto
echo "-----------------" >> toto
touch tata
echo "-----------------" >> tata
echo "- tata file">> tata
echo "-----------------" >> tata
git add toto tata
git commit -m "Initial commit"
echo "echo toto" >> toto
echo "echo tata" >> tata
git commit -am "Add content to file"
cd ..

# Creating main project that will use the subtree
mkdir main_project
cd main_project
git init
touch tutu
echo "-----------------" >> tutu
echo "- tutu file">> tutu
echo "-----------------" >> tutu
git add tutu
git commit -m "Add tutu file"
# Creation of subtree
mkdir sources
git remote add sub_project_remote ../sub_project
git fetch sub_project_remote
git checkout -b sub_project_branch sub_project_remote/master
git checkout master
git read-tree --prefix=sources/sub_project/ -u sub_project_branch
git commit -am "Integration of subtree"

echo "------------------------"
echo "Subtree well integrated "
ls *
ls sources/sub_project
echo "------------------------"

# Go in subtree to remove tata file
cd ../sub_project
echo "#EOF" >> toto
git add toto
git rm tata
git commit -m "Add EOF and remove tata"

# go back in main project to integrate subtree modifications
cd ../main_project
git checkout sub_project_branch
git fetch sub_project_remote
git pull

echo "------------------------"
echo "Check that tata has been removed "
ls *
echo "------------------------"

git checkout master
git diff-tree -p sub_project_branch
git merge -v --squash --no-commit -X subtree=sources/sub_project -X theirs sub_project_branch

echo "------------------------"
echo "Check after merge that tata has been removed "
ls sources/*
echo "------------------------"
git commit -m "Second integration from subtree"
cd ..
#EOF