#!/bin/sh
#
# hg-to-fi - build hg repo from fast-import stream on stdin, or stream a hg repo to stdout
#
# Intended for reposurgeon roundtripping tests with Mercurial.
#
# To add complexity to a test load, do -n, then edit the test repo with
# hg, then use -d.
#
# With the -e option, specify using the Mercurual extractor rarther than
# the native support.
#
# 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 environment variable is specified, 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.
#
# 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.
#
. ./common-setup.sh

# Required because $PWD seems to be undefined in Gitlab's CI environment
BIN="${BINDIR:-$(realpath ..)}"

build=True
stream=True
cleanup=True
extract=""
verbose=0

pecho() { printf %s\\n "$*"; }
log() { pecho "$@"; }
error() { log "ERROR: $@" >&2; }
fatal() { error "$@"; exit 1; }
try() { "$@" || fatal "'$@' failed"; }

while getopts noe opt
do
    case $opt in
	n) build=True ;  stream=False ; cleanup=False ;;
	o) build=False ; stream=True  ; cleanup=False ;;
	e) extract='prefer hg-extractor'
    esac
done
shift $(($OPTIND - 1))

tmpdir=${TMPDIR:-/tmp}

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

# Should we build a repo from the input file?
if [ $build = True ]
then
	# Go via git, because hg convert is standard and hg fastimport isn't
    try rm -fr $testrepo.git $testrepo
    try mkdir $testrepo.git $testrepo
    (
        try cd $testrepo.git >/dev/null
        try git init --quiet
        try git fast-import --quiet
        try git checkout
    ) || exit 1
    try hg --config extensions.convert= convert $testrepo.git $testrepo \
        > /dev/null
    try rm -fr $testrepo.git
fi

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

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