#!/usr/bin/bash
# MKit - simple install helper
# See LICENSE file for copyright and license details.

mkit_import build
mkit_import ini
mkit_import target
mkit_import util

VDK_TEST_SHELL__UTILDIR=${VDK_TEST_SHELL__UTILDIR:-/usr/share/vdk/utils}

vdk_test_shell__main() {
    #
    # Run tests
    #
    local BinPath="$VDK_TEST_SHELL__UTILDIR/vdk_test"
    local ModName
    local ProjVersion
    local ProjLastGitSummary
    local es=0
    local Clean
    local Shell
    test -x "$BinPath" || die "no such executable: $BinPath"
    Shell=$(__vdk_test_shell__load_shell)
    Clean=$(__vdk_test_shell__load_clean) || return 3
    target__run build
    target__run _mkit_metadata
    ProjVersion=$(build__cached semver)
    ProjLastGitSummary=$(build__cached git_lastsummary)
    warn " .. __MKIT_PROJ_VERSION__ = $ProjVersion" \
         " .. __MKIT_PROJ_GIT_LASTSUMMARY__ = $ProjLastGitSummary"
    ModName=$(ini 1value macros:__VDK_PYLIB_MODNAME__)
    build__recordr vdk_test
    debug_var Shell Clean
    __vdk_test_shell__runshell; es=$?
    __vdk_test_shell__clean "$es"
    return $es
}

__vdk_test_shell__clean() {
    #
    # Clean up after shell if exit status $1 is OK
    #
    # We've registered our sub-dir to MKit so its
    # native cleanup will suffice.
    #
    local es=$1
    case $es:$Clean in
        0:onpass)   target__run clean ;;
        *:onpass)   warn "skipping clean; vdk_test shell failed with: $es" ;;
        *:always)   target__run clean ;;
        *:never)    true ;;
        *)          warn "bug: invalid option value: clean=$Clean"
                    return 3 ;;
    esac
}

__vdk_test_shell__load_clean() {
    #
    # Safely load 'clean' option
    #
    local allowed=(onpass always never)
    util__loadenv_enum VDK_TEST_SHELL__CLEAN "${allowed[@]}" && return 0
    plugin__option_enum clean "${allowed[@]}" && return 0
    warn "falling back to: clean = onpass" \
         " .. set VDK_TEST_SHELL__CLEAN or [options:vdk_test_shell:clean]" \
         " .. to onpass|always|never to change it"
    echo onpass
}

__vdk_test_shell__load_shell() {
    #
    # Safely load interpreter name for the shell
    #
    util__loadenv VDK_TEST_SHELL__SHELL && return 0
    plugin__option_single "shell" && return 0
    warn "falling back to: shell = bash" \
         " .. set VDK_TEST_SHELL__SHELL or [options:vdk_test_shell:shell]" \
         " .. to valid command interpreter to change it"
    echo bash
}

__vdk_test_shell__runshell() {
    #
    # Run the shell
    #
    local es
    util__warnbox "→" "running the shell"
    (
        export VDK_TEST__BUILDDIR="src/$ModName"
        "$BinPath" "$ModName" shell "$Shell"
    ); es=$?
    test "$es" -eq 0 && return 0
    util__warnbox "↑" \
        "shell exites with non-zero exit status: $es" \
        "at $ProjVersion" \
        ".. ($ProjLastGitSummary)"
    return "$es"
}
