#!/bin/bash
set -euo pipefail

dn=$(cd $(dirname $0) && pwd)

export topsrcdir=$(cd $dn/.. && pwd)
. ${dn}/common/libtest-core.sh
. ${dn}/common/libcomposetest.sh

# avoid refetching yum metadata everytime
export RPMOSTREE_USE_CACHED_METADATA=1

LOGDIR=${LOGDIR:-$(pwd)/test-compose-logs}
mkdir -p ${LOGDIR}

colour_print() {
  colour=$1; shift
  [ ! -t 1 ] || echo -en "\e[${colour}m"
  echo -n "$@"
  [ ! -t 1 ] || echo -en "\e[0m"
  echo
}

pass_print() {
  colour_print 32 "$@" # green
}

fail_print() {
  colour_print 31 "$@" # red
}

skip_print() {
  colour_print 34 "$@" # blue
}

uid=$(id -u)
test_compose_datadir=/var/tmp/rpmostree-compose-cache-${uid}
export test_compose_datadir
mkdir -p ${test_compose_datadir}
datadir_owner=$(stat -c '%u' ${test_compose_datadir})
test ${uid} = ${datadir_owner}

# Create a consistent cache of the RPMs
echo "Preparing compose tests..."
tmp_repo=${test_compose_datadir}/tmp-repo
if test -z "${RPMOSTREE_COMPOSE_CACHEONLY:-}"; then
    mkdir -p ${test_compose_datadir}/cache
    setup_rpmmd_repos ${dn}/composedata
    ostree --repo=${tmp_repo} init --mode=bare-user
    # We use rpm-ostree in dry-run --cachedir mode
    rpm-ostree compose --repo=${tmp_repo} tree --download-only --cachedir=${test_compose_datadir}/cache ${dn}/composedata/fedora-base.json
    (cd ${test_compose_datadir}/cache && createrepo_c .)
fi
rm ${tmp_repo} -rf

total=0
pass=0
fail=0
skip=0
all_tests="$(cd ${dn}/compose-tests && ls test-*.sh | sort)"
tests=""
if [ -n "${TESTS+ }" ]; then
    for tf in ${all_tests}; do
        tfbn=$(basename "$tf" .sh)
        tfbn=" ${tfbn#test-} "
        if [[ " $TESTS " != *$tfbn* ]]; then
            echo "Skipping: ${tf}"
            continue
        fi
        tests="${tests} ${tf}"
    done
else
    tests="${all_tests}"
fi

if test -z "${tests}"; then
    fatal "error: No tests match ${TESTS}"
fi

echo "Compose tests starting: $(date)"
echo "Executing: ${tests}"
echo "Writing logs to ${LOGDIR}"
function postprocess_logs() {
    # Help out S3 to have the right MIME type
    for x in ${LOGDIR}/1/*.sh; do
        if test -d ${x}; then
            mv ${x}/{stdout,output.txt}
            rm ${x}/stderr
        fi
    done
}
trap postprocess_logs EXIT
# Note we merge stdout/stderr here since I don't see value
# in separating them.
(for tf in ${tests}; do echo $tf; done) | \
    parallel -j +1 --progress --halt soon,fail=1 \
             --results ${LOGDIR} /bin/sh -c "${dn}/compose-tests/{} 2>&1" |& tail
echo "$(date): All tests passed"
