#!/bin/bash
set -euo pipefail

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

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

# avoid refetching yum metadata everytime
export RPMOSTREE_USE_CACHED_METADATA=1

export 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... $(date)"
tmp_repo=${test_compose_datadir}/tmp-repo
if test -z "${RPMOSTREE_COMPOSE_CACHEONLY:-}"; then
    setup_rpmmd_repos ${dn}/composedata
    ostree --repo=${tmp_repo} init --mode=bare-user
    # Ensure all subsequent tests have the RPMs
    mkdir -p ${test_compose_datadir}/{fedora-local,cache}
    rpm-ostree compose --repo=${tmp_repo} tree --download-only-rpms --cachedir=${test_compose_datadir}/cache ${dn}/composedata/fedora-base.json
    find ${test_compose_datadir}/cache/ -name '*.rpm' | while read f; do
        mv $f ${test_compose_datadir}/fedora-local
    done
    (cd ${test_compose_datadir}/fedora-local && createrepo_c .)
fi
echo "Done preparing compose tests! $(date)"
rm ${tmp_repo} -rf

total=0
pass=0
fail=0
skip=0
all_tests="$(cd ${dn}/compose-tests && ls test-*.sh | sort)"
if [ "${RPMOSTREE_COMPOSE_TEST_FILTER:-}" == odd ]; then
  # https://superuser.com/a/101760/237392
  all_tests="$(sed -n 'p;n' <<< ${all_tests})"
elif [ "${RPMOSTREE_COMPOSE_TEST_FILTER:-}" == even ]; then
  all_tests="$(sed -n 'n;p' <<< ${all_tests})"
fi
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}"
(for tf in ${tests}; do echo $tf; done) | \
    parallel -v -j +1 --progress --halt soon,fail=1 \
             --results ${LOGDIR}/parallel --quote /bin/sh -c "${dn}/compose-tests/run-test.sh {}"
echo "$(date): All tests passed"
