#!/bin/sh

set -eu

src_dir="$PWD"

# Fix permissions of a particular test script,
# see https://github.com/latchset/clevis/issues/498
test_perms='src/luks/tests/bind-luks2-ext-token'
if [ "$(stat --format=%a "$test_perms")" != '755' ]; then
    chmod 755 "$test_perms"
else
    echo "FIXME: Workaround for $test_perms is no longer needed"
    exit 1
fi

exit=0

substitute() {
    local dir

    while [ "${1-}" ]; do
        dir="$1"
        shift

        cd "$src_dir/$dir"
        for f in *.in; do
            echo "I: Substituting in $dir/$f"
            sed -e '
s:@SOCAT@:/usr/bin/socat: ;
s:@TANGD_KEYGEN@:/usr/libexec/tangd-keygen: ;
s:@TANGD_UPDATE@:: ;
s:@TANGD@:/usr/libexec/tangd:
s/@OLD_CRYPTSETUP@/0/ ;
s/@OLD_CRYPTSETUP_EXISTING_TOKEN_ID@/0/
' \
                <"$f" >"${f%.in}"
        done
    done
}

get_time_ms() {
    date +%s%N | sed -e 's/[0-9]\{6\}$//'
}

run_tests() {
    local dir

    while [ "${1-}" ]; do
        dir="$1"
        shift

        echo "I: Running tests in $dir"
        cd "$src_dir/$dir"
        for f in $(find . -type f -not -name 'tests-common-functions*' -executable | sort); do
            # Skip hanging test
            if [ "$f" = './default-thp-alg' ]; then
                echo "I: Skipping $f"
                continue
            fi
            echo "I: Running test $f"
            # test are very noisy, keep them silent as long as they pass
            t0="$(get_time_ms)"
            chronic "$f" || exit=$?
            t1="$(get_time_ms)"
            echo "I: ... run time: $((t1 - t0)) ms"
        done
    done
}

substitute 'src/luks/tests' 'src/pins/tang/tests'
export PATH="$src_dir/src/pins/tang/tests:$src_dir/src/luks/tests:$PATH"

run_tests 'src/luks/tests' 'src/pins/tang/tests' 'src/pins/pkcs11/tests'

exit $exit
