#/bin/bash

## set -e explicitly
set -e

## set current directory as working directory
wd=`pwd`

## create repositories to be used as submodules
mkdir sub1 sub2 remote
(cd sub1
    git init
    echo "test sub1" >> file
    git add file
    git commit -m "initial commit sub1"
)
git clone --bare sub1 remote/sub1.git
(cd sub2
    git init
    echo "test sub2" >> file
    git add file
    git commit -m "initial commit sub2"
)
git clone --bare sub2 remote/sub2.git

## create super repository
git init --bare remote/super.git
git clone remote/super.git super
(cd super
    git submodule add $wd/remote/sub1.git sub
    git commit -m "Added submodule sub1 as sub"
    git push -u origin master
)

## clone super repository again
## and switch submodule sub1 by sub2
git clone --recursive remote/super.git super2
(cd super2
    ## remote submodule sub
    git config --remove-section submodule.sub
    git rm .gitmodules
    rm -rf sub
    git rm sub
    git commit -m "Removed submodule sub"
    ## add submodule sub2 as sub
    git submodule add $wd/remote/sub2.git sub
    git commit -m "Added submodule sub2 as sub"
    git push
)

## now pull super
(cd super
    git pull
    ## this will fail
    git submodule update --init || echo "submodule update fails, that's ok"
    ## so sync first und update again
    git submodule sync
    git submodule update --init
    ## now sub is corrupt
    (cd sub
	git log master ## this is from sub1
	git log origin/master ## this is from sub2
    )
)