#!/bin/sh
#
# Test reposurgeon branch naming issue with hg repo
#
# This test cannot use the usual hg-to-fi script because we
# want to test the behavior of the actual hg tag command and
# how its results appear to the hg extractor
#
# The REPOSURGEON environment variable can be used to substitute in a
# different implementation.

# shellcheck disable=SC1091
. ./common-setup.sh

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

need hg

build=True
stream=True
cleanup=True

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

while getopts nr opt
do
    case $opt in
    n) build=True; stream=False ; cleanup=False ;;
    r) build=False; stream=True  ; cleanup=False ;;
    *) echo "$0: unknown option $opt"; exit 1;;
    esac
done
# shellcheck disable=SC2004
shift $(($OPTIND - 1))

testrepo=${1:-/tmp/test-repo$$}

USER='"J. Random Hacker" <jrh@foobar.com>'

# Should we build the repo?
if [ $build = True ]
then
    # Build hg test repo with multiple hg branches
    try rm -fr "$testrepo"
    try hg init "$testrepo" || exit 1
    try cd "$testrepo" >/dev/null
    # The weird --date incantation in the hg commits is to ensure that the commit
    # timestamps match those in the .fi file; the 18000 is because hg wants the time zone
    # offset in seconds west of UTC, for what reason I know not--I know there are weird
    # time zones in the world but I didn't think any of them got down to one-second
    # granularity in offsets...
    (
        try touch file
        try hg add file >/dev/null
        try hg commit --user "$USER" --date "1456976400 18000" -m "First commit" >/dev/null
	try hg tag --user "$USER" --date "1456976401 18000" tag1 >/dev/null
        try hg tag --user "$USER" --date "1456976402 18000" -r tag1 tag2 >/dev/null
        try echo "foobar" >> file
        try hg commit --user "$USER" --date "1456976410 18000" -m "add some more data" >/dev/null
	try hg tag --user "$USER" --date "1456976411 18000" tag3 >/dev/null
        try hg tag --user "$USER" --date "1456976412 18000" -r tag3 tag4 >/dev/null
    ) || exit 1
    try cd - >/dev/null
fi

# Should we stream the repo?
if [ $stream = True ]
then
    echo "#reposurgeon description: from an hg repo with real hg branches; includes multiple tags."
    # shellcheck disable=SC2086
    "${BIN}/${REPOSURGEON:-reposurgeon}" "${BUILDOPT}" ${TESTOPT} "read $testrepo" "sourcetype git" "[.hgtags] & =C remove .hgtags" "gc" "write -"
fi

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