#%Module
# Choose compiler version
#
# This check if any compiler was previously "module loaded", or if no compiler
# previously loaded, will use the default compiler.  Either way, it will check
# if there is a subdirectory matching the compiler family name, and if so
# will default to that.
#
# If no subdirectory matching compiler family name is found, we just return
# without defaulting.  The modulecmd will default based on its internal rules,
# and it is up to the resulting module file to either load an appropriate
# compiler if no compiler is loaded or to abort with appropriate error
# messages if it wants an incompatible compiler.
#
# Usage:
# In most cases, can simply symlink .modulerc to this file
#
# In more complicated cases, .modulerc can source this file, and can
# then test the variable _did_default, which will be true if we set
# a default for modules for the next level, or false otherwise (in which
# case your .modulerc can set one)

# Source some required Tcl procedures here.  Hack for cookbook
# making use of environment variable for location.
# In production, this should ideally be in a site config file.
# At minimum, hardcode the path
set rootdir $::env(MOD_GIT_ROOTDIR)
set tcllibdir $rootdir/doc/example/compiler-etc-dependencies/tcllib
source $tcllibdir/common_utilities.tcl

set moduledir [file dirname $ModulesCurrentModulefile]
set parentdir [ file tail $moduledir ]

# _did_default will be true if we actually default something
# Useful in case a .modulerc sources us, and wants to set a default if we
# did not
set _did_default false

# Get the currently loaded compiler or default, but do not load/prereq it
set compilerTag [ GetLoadedCompiler 1 1 ]

if { $compilerTag ne {} } {
   # Compiler loaded or defaulted
   # Make sure it matches our parent dir
   set tmpCompTag [ GetPackageFamilyVersion $compilerTag ]
   set compilerFamily [ lindex $tmpCompTag 0 ]
   set compilerVersion [ lindex $tmpCompTag 1 ]

   # Convert any gnus to gccs
   set tmp1 $compilerFamily
   if { $tmp1 eq {gnu} } { set tmp1 gcc }
   set tmp2 $parentdir
   if { $tmp2 eq {gnu} } { set tmp2 gcc }

   if { $tmp1 eq $tmp2 } {
      # If reach here, our parent dir agrees with
      # the family of our loaded/defaulted compiler
      if { $compilerVersion ne {} } {
         # We have a version, does a modulefile/dir exist for it
         if [ ChildModuleExists $compilerVersion ] {
            # There is a modulefile/dir for this compiler version, default to it
            module-version $compilerFamily/$compilerVersion default
            set _did_default true
         }
      }
   }
}
