#/bin/bash
# Generate fortran statements to write the output of the module list command
# The --terse option to module command make appear each module name on its own line
OLD_IFS=${IFS}

echo "! Automatically generated file with script gen_module_list.sh" > ${1}

# Check wether module command is available
if [ $(command -v module) ]
then

    # Test whether we should use "module --terse list" or "module list --terse"
    module --terse list &> /dev/null
    if [ $? -eq 0 ]
    then
	module_option="--terse list"
    else
	module list --terse &> /dev/null
	if [ $? -eq 0 ]
	then
	    module_option="list --terse"
	else
	    module_option="list"
	fi
    fi

    echo "module option = ${module_option}"
    echo "! output from \`module ${module_option}\`" > ${1}
    echo 'write(ounit, *)' >> ${1}
    module ${module_option} &> module.list.tmp
    #module list --terse &> module.list.tmp
    IFS=$'\n'
    for line in $(cat module.list.tmp)
    do
        echo 'write(ounit, '"'"'(a)'"'"') "'${line}'"' >> ${1}
    done
    rm module.list.tmp
else
    echo 'write(ounit, *)' >> ${1}
    echo 'write(ounit, *) "module command is not available"' >> ${1}
fi
IFS=${OLD_IFS}
