#!/bin/bash
set -e -x

cd $(dirname $0)/..

if [ -z "$K3S_IMAGE" ]; then
    . ./scripts/version.sh
    TAG=${TAG:-${VERSION_TAG}${SUFFIX}}
    REPO=${REPO:-rancher}
    IMAGE_NAME=${IMAGE_NAME:-k3s}
    export K3S_IMAGE=${REPO}/${IMAGE_NAME}:${TAG}
fi

OUTPUT=$(pwd)/dist/artifacts
mkdir -p ${OUTPUT}

pids=()
output=()

show-logs() {
    for pid in "${pids[@]}"; do
        logdir=$(pwd)/logs/${pid}
        if [ ! -d $logdir ]; then
            continue
        fi
        echo
        echo "#- Begin: logs for sonobuoy run pid ${pid}"
        for log in $(pwd)/logs/${pid}/*.log; do
            if [ -f ${log} ]; then
                echo
                echo "#- Tail: ${log}"
                tail -10 ${log}
                echo "#- Done: ${log}"
                echo
            fi
        done
        echo "#- Finish: logs for sonobuoy run pid ${pid}"
        echo
    done
}

cleanup() {
    exit_status=$?
    set +e
    trap - EXIT INT
    kill ${pids[@]} 2>/dev/null
    wait
    set +x
    echo -n "Tests "
    if [ "${exit_status}" -eq "0" ]; then
        echo "passed"
    else
        echo "failed"
        show-logs
    fi
    exit ${exit_status}
}
trap cleanup EXIT INT


# ---

run-sonobuoy() {
    output+=(${log_output})
    E2E_LOG_OUTPUT=${log_output} \
        ./scripts/sonobuoy ${@} \
            > >(stdbuf -oL sed "s/^/[${label}] /") 2>&1 &
    pids+=($!)
}

log_output=${OUTPUT}/e2e-STATUS-${ARCH}-parallel.log label=PARALLEL \
    run-sonobuoy --e2e-focus='\[Conformance\]' --e2e-skip='\[Serial\]' --e2e-parallel=y

sleep 60

log_output=${OUTPUT}/e2e-STATUS-${ARCH}-serial.log label=SERIAL \
    run-sonobuoy --e2e-focus='\[Serial\].*\[Conformance\]'

exit_code=0
for pid in "${pids[@]}"; do
    wait $pid || exit_code=$?
done
exit ${exit_code}
