#!/bin/sh
#
# fi-to-fi - build repo from fast-import stream on stdin, or stream repo to stdout
#
# Intended for reposurgeon roundtripping tests.
#
# With the -g option, build a repo from the stream input and view it
# for gitk.  Useful for eyeball-checking whether the DAG has the
# shape you think it should.
#
# With the -n option, create a repo corresponding to the input file
# and check out a working copy for editing, but do not stream the
# result to stdout and do not delete the repo.  A following argument,
# if present, becomes the name of the repo; otherwise, it is created 
# under $TMPDIR if that environmeent variable is set, falling
# back to /tmp.
#
# With the -o option, expect the repo to exist, and throw a
# stream dump to stdout; then do not delete the repo.
#
# To add complexity to a test load, do -n, then edit the test repo with
# git, then use -o.
#
# The REPOSURGEON environment variable can be used to substitute in a
# different implementation.
#
# The TESTOPT variable can be used to pass an early command or option setting
# to reposurgeon.
#
BIN=${PWD}/..

extract=True
view=False0
stream=True
cleanup=True

tmpdir=${TMPDIR:-/tmp}

while getopts gno opt
do
    case $opt in
	g) extract=True ;  view=True; stream=False ; cleanup=False ;;
	n) extract=True ;  view=False; stream=False ; cleanup=False ;;
        o) extract=False ; view=False; stream=True  ; cleanup=False ;;
    esac
done
shift $(($OPTIND - 1))

# This lets us set the repo location 
testrepo=${1:-${tmpdir}/test-repo$$}

# Should we build a repo from the input file?
if [ $extract = True ]
then
    rm -fr $testrepo; mkdir $testrepo
    (cd $testrepo >/dev/null; git init --quiet; git fast-import --quiet; git checkout) 
fi

# Should we view the repo?
if [ $view = True ]
then
    (cd $testrepo >/dev/null; gitk --all --tags)
fi

# Should we stream the repo?
if [ $stream = True ]
then
    ${BIN}/${REPOSURGEON:-reposurgeon} "${TESTOPT}" "prefer git-extractor" "read $testrepo" "write -"
fi

# Should we clean up the test directory
if [ $cleanup = True ]
then
    rm -fr $testrepo test-checkout
fi
