#!/bin/bash
. /usr/share/beakerlib/beakerlib.sh || exit 1

rlJournalStart
    rlPhaseStartSetup
        rlRun "run=\$(mktemp -d)" 0 "Create run directory"
        rlRun "pushd data"
    rlPhaseEnd

    function replace_fmf_root () {
        local recipe=$1
        local temp_recipe=$(mktemp)
        yq ".run.root = \"$PWD\"" "$recipe" > "$temp_recipe"
        mv "$temp_recipe" "$recipe"
    }

    rlPhaseStartTest "Test recipe loading with library dependencies"
        replace_fmf_root "local.yaml"
        rlRun -s "tmt run -vvv --scratch --id $run --recipe local.yaml"
        rlAssertGrep "name: discover-fmf" $rlRun_LOG
        rlAssertGrep "name: discover-shell" $rlRun_LOG
        rlAssertGrep "summary: 3 tests selected" $rlRun_LOG
        rlAssertGrep "environment: PROVISION_ENV: provision_value" $rlRun_LOG
        rlAssertGrep "script: echo \"Prepare phase\"" $rlRun_LOG
        rlAssertGrep "name: Execute phase" $rlRun_LOG
        rlAssertGrep "pass /discover-fmf/tests/first" $rlRun_LOG
        rlAssertGrep "pass /discover-fmf/tests/second" $rlRun_LOG
        rlAssertGrep "pass /discover-shell/shell-test" $rlRun_LOG
        rlAssertGrep "summary: 3 tests executed" $rlRun_LOG
        rlAssertGrep "script: echo \"Finish phase\"" $rlRun_LOG
        rlAssertGrep "total: 3 tests passed" $rlRun_LOG
    rlPhaseEnd

    rlPhaseStartTest "Test recipe loading with remote repository"
        replace_fmf_root "remote.yaml"
        rlRun -s "tmt run -vvv --scratch --id $run --recipe remote.yaml"
        rlAssertGrep "summary: 1 test selected" $rlRun_LOG
        rlAssertGrep "pass /tests/one" $rlRun_LOG
        rlAssertGrep "summary: 1 test executed" $rlRun_LOG
        rlAssertGrep "total: 1 test passed" $rlRun_LOG
    rlPhaseEnd

    rlPhaseStartTest "Test recipe loading of imported plan"
        replace_fmf_root "import.yaml"
        rlRun -s "tmt run -vvv --scratch --id $run --recipe import.yaml"
        rlAssertGrep "summary: 2 tests selected" $rlRun_LOG
    rlPhaseEnd

    rlPhaseStartTest "Test recipe loading of minimal plan"
        replace_fmf_root "minimal.yaml"
        rlRun -s "tmt run -vvv --scratch --id $run --recipe minimal.yaml"
        rlAssertGrep "summary: 1 test selected" $rlRun_LOG
        rlAssertGrep "total: 1 test passed" $rlRun_LOG
        rlAssertGrep "Execute script" $rlRun_LOG
    rlPhaseEnd

    rlPhaseStartCleanup
        rlRun "popd"
        rlRun "rm -r $run" 0 "Remove run directory"
    rlPhaseEnd
rlJournalEnd
