# SPDX-License-Identifier: GPL-2.0-only

bats = find_program('bats', required: false)
kcov = find_program('kcov', required: false)

test_cases = [
    'bash-completion.bats',
    'extglob.bats',
    'functions.bats',
    'mkinitcpio.bats',
    'parse_cmdline.bats',
    'zsh-completion.bats',
    'tpm2.bats',
]

# Copy test files to build directory
foreach t : test_cases
    configure_file(
        input: 'cases' / t,
        output: t,
        copy: true
    )
endforeach

mkinitcpio_path = mkinitcpio_target.full_path()
lsinitcpio_path = lsinitcpio_target.full_path()

coverage_dirs = []

test_env = environment({
    'LC_ALL': 'C.UTF-8',
    'MESON_TEST': '1',
    'MKINITCPIO': mkinitcpio_path,
    'LSINITCPIO': lsinitcpio_path,
})

if not bats.found()
    subdir_done()
endif

foreach t : test_cases
    test(t,
        bats,
        args: [join_paths(meson.current_source_dir(), 'cases', t)],
        depends: [mkinitcpio_target, lsinitcpio_target],
        workdir: meson.current_source_dir(),
        env: test_env,
    )

    if kcov.found()
        test(
            'coverage-' + t,
            kcov,
            args: [
                '--include-path=.', '--exclude-path=test', '--collect-only',
                project_build_root / 'coverage-' + t,
                bats.full_path(), meson.current_source_dir() / 'cases' / t,
            ],
            env: test_env,
            workdir: meson.current_source_dir(),
            verbose: true,
            timeout: 600,
            suite: 'coverage',
        )
        coverage_dirs += project_build_root / 'coverage-' + t
    endif
endforeach

# merge all coverage results after all other tests run
if kcov.found()
    test(
        'merge-coverage',
        kcov,
        args: [
            '--merge', project_build_root / 'coverage', coverage_dirs,
        ],
        workdir: project_build_root,
        verbose: true,
        is_parallel: false,
        priority: -1000,
        timeout: 600,
        suite: 'coverage',
    )
endif
