#!/bin/sh
# @file mygit-test.sh - Test shared repository work flow

set -u;
set -e;

#set_x="set -x";
set_x="${set_x-:}";
$set_x;

init()
{
    testdir="mygit-tests";
    file="foo";
    tab=$(printf "\t");

    # Allow global control of calls
    git=$(which git);
    git() { $git "$@"; }

    cleanup;
    mkdir "$testdir";
    # Make testdir absolute:
    testdir=`cd "$testdir"; pwd`;
    cd "$testdir";

    a="$testdir/repo_a";
    b="$testdir/repo_b";
    c="$testdir/repo_c";

    int="integr";
    dev="devel";
}

cleanup() {
    rm -rf "$testdir" || true;
}

status() {
    if git status; then :;
    else echo "git status returned $?"; fi;
}

head() { git log "--pretty=format:%H" -1 "$1" --; }

origin_init() {
    name="$1"; shift;
    dir="$1"; shift;
    mkdir "$dir";
    (
	cd "$dir";
	git init; status;

	# Can't checkout because the branch is not yet born
	#git checkout -b "$dev"; status;
	git symbolic-ref HEAD "refs/heads/$name-$dev"; status;
	echo "bar" > "$file"; status;
	git add .; status;
	git commit -m "Initial"; status;

	git branch -a "$int"; status;
	#gitk --all;
	git branch -v;
	[ $(head "$name-$dev") = $(head "$int") ];
	);
}

clone() {
    name="$1"; shift;
    src="$1"; shift;
    dst="$1"; shift;
    #pwd;
    #mkdir "$dst";
    git clone --no-checkout "$src" "$dst";
    (
	cd "$dst";
	git remote -v show;
	git remote -v show origin;
	git remote -v show | grep "origin$tab$src";
	git checkout -b "$int" "origin/$int";
	git checkout -b "$name-$dev";

	echo "changed source from $dst" >> "$file";
	git commit -m "Change by $dst" -a;

	git pull --rebase origin "$int";
	[ `head "$int"` = `head "origin/$int"` ];
	[ `git merge-base "$int" "$name-$dev"` = `head "$int"` ];
	git rebase "$int" "$name-$dev";

	git pull --rebase origin "$int";
	git rebase "$name-$dev" "$int";

	git push origin "$int";
	git checkout "$name-$dev";
	);
}

work()
{
    origin_init "a" "$a";
    # "file://" syntax avoids implied "--local"
    clone "b" "file://$a" "$b";
    clone "c" "file://$a" "$c";

    (
	cd "$a";
	git rebase "$int" "a-$dev";
	cat "$file";
	grep "changed source from $b" "$file";
	grep "changed source from $c" "$file";
	);
}

main() {
    init "$@";
    work;
    #cleanup;
}

main "$@";

# EOF
