#!/usr/bin/env -S bats --report-formatter junit --formatter tap
# -*-sh-*-

source ./common/test_helper_functions.bash || exit 1
source ./common/functions                  || exit 1

if [ -s ./common/TEST_ENV ];then
    source ./common/TEST_ENV
fi

PKG=R
testname=R
module=R
rpm=R-${LMOD_FAMILY_COMPILER}${DELIM}

# Query local compiler family
check_compiler_family CC CXX FC

@test "[$testname] Verify $module module is loaded and matches rpm version ($LMOD_FAMILY_COMPILER)" {
    module list $module/ | grep "1) $module" >& .cmd_output || exit 1
    run grep $module .cmd_output 
    assert_success
    
   # check version against rpm
    local version="$(rpm -q --queryformat='%{VERSION}\n' $rpm)"
    run cat .cmd_output
    assert_output "  1) $module/$version"

    # check binary version against rpm
    R --version | head -1 | awk '{print $3}' >& .cmd_output
    run cat .cmd_output
    assert_output $version
    
}

@test "[$testname] Verify ${PKG}_DIR is defined and exists ($LMOD_FAMILY_COMPILER)" {
    DIR=${PKG}_DIR
    if [ -z ${!DIR} ];then
        flunk "${PKG}_DIR directory not defined"
    fi
    
    if [ ! -d ${!DIR} || -z "${!DIR}" ];then
        flunk "directory ${!DIR} does not exist"
    fi 
}

@test "[$testname] Verify availability of $module executable -> R ($LMOD_FAMILY_COMPILER)" {
    run which R
    assert_success
}


@test "[$testname] Verify availability of $module executable -> Rscript ($LMOD_FAMILY_COMPILER)" {
    run which Rscript
    assert_success
}

# --------------
# SHARE Tests
# --------------

@test "[$testname] Verify module ${PKG}_SHARE is defined and exists ($LMOD_FAMILY_COMPILER)" {
    SHARE=${PKG}_SHARE

    if [ -z ${!SHARE} ];then
        flunk "${PKG}_SHARE directory not defined"
    fi
    
    if [ ! -d ${!SHARE} || -z "${!SHARE}" ];then
        flunk "directory ${!SHARE} does not exist"
    fi 
}


# Execution Test(s)

@test "[$testname] Running bench.R test" {

    run Rscript ./bench.R
    assert_success
}

@test "[$testname] Verify ability to compile C code for R and execute" {

    # Compile C code
    rm -f foo.so 

    run R CMD SHLIB foo.c
    assert_success
    run ls -l foo.so
    assert_success

    # Verify execution
    run Rscript ./test_foo.R
    assert_success
}

