modulecmd.in 27.2 KB
Newer Older
1 2 3 4 5
#!@PMODULES_HOME@/bin/bash

declare -r  PMODULES_DIR=$( cd "$(dirname $0)/.." && pwd )
declare -r  version='@PMODULES_VERSION@'
declare -r  modulecmd="${PMODULES_DIR}/bin/modulecmd.tcl"
6 7 8

declare -rx TCL_LIBRARY="${PMODULES_DIR}/lib/tcl8.6"
declare -rx PSI_LIBMODULES="${PMODULES_DIR}/lib/libmodules.tcl"
9 10 11 12

declare -r modulepath_root="${PSI_PREFIX}/${PSI_MODULES_ROOT}"
declare -ra modulepath=( ${MODULEPATH//:/ } )

13 14
source "${PMODULES_DIR}/lib/libpmodules.bash"

15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
if set -o | grep 'xtrace' | grep -q 'on'; then
        declare -r __XTRACE__='on'
else
        declare -r __XTRACE__='off'
fi

declare output_function='human_readable_output'
declare verbosity='silent'
declare userlvl='expert'
declare sw_force='no'
declare sw_create='no'


print_version() {
	echo "
Pmodules ${version} using Tcl Environment Modules @MODULES_VERSION@
Copyright GNU GPL v2
" 1>&2
}

usage() {
	print_version
	echo "
Usage: module [ switches ] [ subcommand ] [subcommand-args ]

Switches:
        -H|--help               this usage info
        -V|--version            modules version & configuration options
        -f|--force              force active dependency resolution
        -t|--terse              terse    format avail and list format
        -l|--long               long     format avail and list format
        -h|--human              readable format avail and list format
        -v|--verbose            enable  verbose messages
        -s|--silent             disable verbose messages
        -c|--create             create caches for avail and apropos
        -i|--icase              ignored
        -u|--userlvl <lvl>      set user level to (nov[ice],exp[ert],adv[anced])
52
Available SubCommands and Args:
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404
        + add|load              modulefile [modulefile ...]
        + rm|unload             modulefile [modulefile ...]
        + switch|swap           [modulefile1] modulefile2
        + display|show          modulefile [modulefile ...]
        + avail                 [modulefile [modulefile ...]]
        + search [ switches ]   [ args ]
        + use [-a|--append]     [dir|family|release ...]
        + unuse                 dir|family|release [dir|family|release ...]
        + update
        + refresh
        + purge
        + list
        + clear
        + help                  [modulefile|subcommand]
        + whatis                [modulefile [modulefile ...]]
        + apropos|keyword       string
        + initadd               modulefile [modulefile ...]
        + initprepend           modulefile [modulefile ...]
        + initrm                modulefile [modulefile ...]
        + initswitch            modulefile1 modulefile2
        + initlist
        + initclear
	+ sync [ switches ]
" 1>&2

}


subcommand_help_add() {
	echo "
add     modulefile...
load    modulefile...
                Load modulefile(s) into the shell environment. Loading a
		'family-head' will extend the MODULEPATH. E.g.: loading a 
		compiler makes additional modules like openmpi and libraries
		compiled with this compiler available.
" 1>&2
}

subcommand_help_load() {
	subcommand_help_add
}

subcommand_help_rm() {
	echo "
rm      modulefile...
unload  modulefile...
                Remove modulefile(s) from the shell environment. Removing
		a 'family-head' will also unload all modules in the family.
" 1>&2
}

subcommand_help_unload() {
	subcommand_help_rm
}

subcommand_help_switch() {
	echo "
switch  [modulefile1] modulefile2
swap    [modulefile1] modulefile2
		Switch loaded modulefile1 with modulefile2. If modulefile1
		is not specified, then it is assumed to be the currently
		loaded module with the same root name as modulefile2.
" 1>&2
}

subcommand_help_swap() {
	subcommand_help_switch
}

subcommand_help_display() {
	echo "
display modulefile...
show    modulefile...
		Display information about one or more modulefiles.  The
		display sub-command will list the full path of the
		modulefile(s) and all (or most) of the environment changes
		the modulefile(s) will make if loaded.  It will not display
		any environment changes found within conditional statements.
" 1>&2
}

subcommand_help_show() {
	subcommand_help_display
}

subcommand_help_apropos() {
	echo "
apropos string
keyword string	Seeks through the 'whatis' informations of all modulefiles for
		the specified string.  All module-whatis informations matching
		the string will be displayed.
		
" 1>&2
}

subcommand_help_keyword() {
	subcommand_help_apropos
}


subcommand_help_avail() {
	echo "
avail string    List all available modulefiles in the current MODULEPATH. If
		an argument is given, then each directory in the MODULEPATH
		is searched for modulefiles whose pathname match the argument.

		This command does *not* display all installed modules on the
		system. Only *loadable* modules are listed.  The list of 
		available modules may change either by loading other modules,
		e.g. a compiler, or with the sub-command 'use'.
" 1>&2
}

subcommand_help_search() {
	echo "
search [switches] STRING...
		Search installed modules. If an argument is given, search
		for modules whose name match the argument.

SWITCHES: 
--no-header	Suppress output of a header.

--release=RELEASE
		Search for modules within this release. You can specify this
		switch multiple times.  Without this switch, the used releases
		will be searched.

-a|--all-releases
		Search within all releases.
		
--with=STRING
		Search for modules compiled with modules matching string. The
		command

		module search --with=gcc/4.8.3

		lists all modules in the hierarchy compiled with gcc 4.8.3.
" 1>&2
}

subcommand_help_use() {
	echo "
use [-a|--append|-p|--prepend] [directory|family|release...]
		Without arguments this sub-command displays information about
		the module search path, used families and releases. You can
		use this sub-command to get a list of available families and
		releases.

		With a directory as argument, this directory will either be
		prepended or appended to the module search path. The default
		is to prepend the directory.

		With a family as argument, the modules in this family will 
		be made available.

		With a release as argument, this modules with this release
		will be made available. 
" 1>&2
}

subcommand_help_unuse() {
	echo "
unuse directory|family|release...
		Remove the given directory, family or release from the search
		path.
" 1>&2
}
subcommand_help_update() {
	echo "
update		Attempt  to  reload  all  loaded  modulefiles.
" 1>&2
}

subcommand_help_refresh() {
	echo "
refresh		Force a refresh of all non-persistent components of currently
		loaded modules.  This should be used on derived shells where
		aliases need to be reinitialized but the environment variables
		have already been set by the currently loaded modules.
" 1>&2
}

subcommand_help_purge() {
	echo "
purge		Unload all loaded modulefiles.
" 1>&2
}

subcommand_help_list() {
	echo "
list		List loaded modules.
" 1>&2
}

subcommand_help_clear() {
	echo "
clear		Force the Modules package to believe that no modules are
		currently loaded.
" 1>&2
}

subcommand_help_whatis() {
	echo "
whatis [modulefile...]
                Display the information set up by the module-whatis commands
		inside the specified modulefile(s). If no modulefile is
		specified, all 'whatis' lines will be shown.
" 1>&2
}

subcommand_help_initadd() {
	echo "
initadd	modulefile...
		Add modulefile(s) to the shell's initialization file in the
		user's home directory.  The startup files checked (in order)
		are:

                    csh -   .modules, .cshrc(.ext), .csh_variables, and
                            .login(.ext)
                    tcsh -  .modules, .tcshrc, .cshrc(.ext), .csh_variables,
                            and .login(.ext)
                    (k)sh - .modules, .profile(.ext), and .kshenv(.ext)
                    bash -  .modules, .bash_profile, .bash_login,
                            .profile(.ext) and .bashrc(.ext)
                    zsh -   .modules, .zcshrc(.ext), .zshenv(.ext), and
                            .zlogin(.ext)

                If a 'module load' line is found in any of these files, the
                modulefile(s) is(are) appended to any existing list of 
                modulefiles.  The 'module load' line must be located in at
                least one of the files listed above for any of the 'init'
                sub-commands to work properly.  If the 'module load' line
                line is found in multiple shell initialization files, all
		of the lines are changed.
" 1>&2
}

subcommand_help_initprepend() {
	echo "
initprepend modulefile...
		Does the same as initadd but prepends the given modules to
		the beginning of the list.
" 1>&2
}

subcommand_help_initrm() {
	echo "
initrm modulefile...
		Remove modulefile(s) from the shell's initialization files.
" 1>&2
}

subcommand_help_initswitch() {
	echo "
initswitch modulefile1 modulefile2
		Switch modulefile1 with modulefile2 in the shell's initialization files.
" 1>&2
}

subcommand_help_initlist() {
	echo "
initlist	List all of the modulefiles loaded from the shell's initialization file.
" 1>&2
}

subcommand_help_initclear() {
	echo "
initclear	Clear all of the modulefiles from the shell's initialization files.
" 1>&2
}

subcommand_help_sync() {
	echo "
sync [--from=DIR] [--to=DIR] [--dryrun] [--delete] 
		Synchronize two Pmodules hierarchies.
" 1>&2
}

append_path () {
        local -r P=$1
        local -r d=$2

        if ! echo ${!P} | egrep -q "(^|:)${d}($|:)" ; then
                if [[ -z ${!P} ]]; then
                        eval $P=${d}
                else
                        eval $P=${!P}:${d}
                fi
        fi
}

prepend_path () {
        local -r P=$1
        local -r d=$2

        if ! echo ${!P} | egrep -q "(^|:)${d}($|:)" ; then
                if [[ -z ${!P} ]]; then
                        eval $P=${d}
                else
                        eval $P=${d}:${!P}
                fi
        fi
}

remove_path() {
        local -r P=$1
        local -r d=$2
	local new_path=''
	local -r _P=( ${!P//:/ } )
	# loop over all entries in path
	for entry in "${_P[@]}"; do
		[[ "${entry}" != "${d}" ]] && new_path+=":${entry}"
	done
	# remove leading ':'
	eval ${P}="${new_path:1}"
}

module_is_available() {
	is_loadable() {
		release=$( get_release "$1" )			
		[[ :${PSI_USED_RELEASES}: =~ ${release} ]] && return 0
		return 1
	}

	[[ -f $1 ]] && return 0
	for dir in "${modulepath[@]}"; do
		if [[ -d ${dir}/$1 ]]; then
			while read fname; do
				is_loadable "${fname}" && return 0			
			done < <(find "${dir}" -type l -o -type f  \! -name ".*")
		else
			[[ -f ${dir}/$1 ]] || continue
 			[[ -r ${dir}/$1 ]] || continue
		        is_loadable "${dir}/$1" && return 0
		fi
	done
	return 1
}

get_release() {
	local -r modulefile=$1
	local -r releasefile="${modulefile%/*}/.release-${modulefile##*/}"
	if [[ -r ${releasefile} ]]; then
		local -r data=$( < "${releasefile}" )
		local -r release=$( echo ${data} )
	else	
		local -r release='unstable'
	fi
	echo ${release}
}

405 406
if [[ -n ${PSI_RELEASES} ]]; then
        declare -r available_releases="${PSI_RELEASES}"
407 408
else
	# set defaults, if file doesn't exist or isn't readable
409
	declare -r available_releases=':unstable:stable:deprecated:'
410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573
fi
declare used_releases=":${PSI_USED_RELEASES}:"

is_release() {
	[[ ${available_releases} =~ :$1: ]]
}

is_used_release() {
	[[ ${used_releases} =~ :$1: ]]
}

declare used_families=":${PSI_LOADEDFAMILIES}:"

is_used_family() {
	[[ ${used_families} =~ :$1: ]]
}

module_is_loaded() {
	[[ :${LOADEDMODULES}: =~ :$1: ]]
}

subcommand_generic0() {
	local -r subcommand=$1
	shift
	if [[ $# != 0 ]]; then
	        echo "${subcommand}: no arguments allowed" 1>&2
		return 3
	fi
	"${modulecmd}" "${shell}" "${subcommand}"
}

subcommand_generic0plus() {
	local -r subcommand=$1
	shift
	"${modulecmd}" "${shell}" "${subcommand}" "$@"
}

subcommand_generic1() {
	local -r subcommand=$1
	shift
	if [[ $# != 1 ]]; then
	        echo "${subcommand}: only one argument allowed" 1>&2
		return 3
	fi
	"${modulecmd}" "${shell}" "${subcommand}" "$1"
}

subcommand_generic1plus() {
	local -r subcommand=$1
	shift
	if [[ $# == 0 ]]; then
	        echo "${subcommand}: missing argument" 1>&2
		return 3
	fi
	"${modulecmd}" "${shell}" "${subcommand}" "$@"
}

subcommand_load() {
	output_load_hints() {
		local -ra rels=( ${available_releases//:/ } )
		for rel in "${rels[@]}"; do
			eval $( subcommand_use "${rel}" )
			if module_is_available "${m}"; then
				echo    "${m}: is ${rel}! If you really want to load this module, run" 1>&2 
				echo -e "\tmodule use ${rel}" 1>&2
				echo    "before running" 1>&2
				echo -e "\tmodule load ${m}" 1>&2
				exit 42
			fi
		done
		local something_found='no'
		local -a output=()
		local -a release=()
		local -a loadable=()
		local -i i=0
		local -i n=0
		while read -a line; do
			output[n]="module load ${line[@]:3} ${line[0]}"
			release[n]=${line[1]}
			if [[ ":${PSI_USED_RELEASES}:" =~ "${release[n]}" ]]; then
				loadable[n]='yes'
			else
				loadable[n]='no'
			fi
			n+=1
		done < <(subcommand_search  "${m}" -a --no-header 2>&1)
		if (( n > 0 )); then
			echo "The following modules chain(s) are available:" 1>&2
			for ((i=n-1; i >=0; i--)); do
				echo -en "${output[i]}\t# ${release[i]}" 1>&2
				if [[ "${loadable[i]}" == "no" ]]; then
				    echo -e "\t# ${release[i]}" 1>&2
				else
					echo "" 1>&2
				fi
			done
		else
			echo "${m}: module does not exist!" 1>&2
		fi
	}
	
	local -r m=$1
	if module_is_available "${m}"; then
		"${modulecmd}" "${shell}" load "${m}"
	else
		if [[ ${userlvl} = 'novice' ]]; then
			output_load_hints
		else
			echo "${m}: module unavailable" 1>&2
		fi
	fi
}


subcommand_unload() {
	# :FIXME: add dependency tests: don't unload if module is required be
	#	  another module
	subcommand_generic1plus unload "$@"
}

subcommand_swap() {
	if [[ $# == 0 ]]; then
	        echo "${subcommand}: missing argument" 1>&2
		return 3
	fi
	if [[ $# > 2 ]]; then
	        echo "${subcommand}: to many arguments" 1>&2
		return 3
	fi
	"${modulecmd}" "${shell}" swap "$@"
}

subcommand_show() {
	subcommand_generic1plus show "$@"
}

#
# get all available modules in given directory.
# return list like
#	modulename1 release1 modulename2 release2 ...
#
get_available_modules() {
	local -r dir=$1
	local -r module=$2
	local -r use_releases=${3:-${PSI_USED_RELEASES}}
	local -a mods=()
	while read mod; do
		local release=$( get_release "${dir}/${mod}" )

		if [[ :${use_releases}: =~ :${release}: ]]; then
		    mods+=( "${mod}" ${release} )
		fi
	done < <(MODULEPATH="${dir}" "${modulecmd}" bash -t avail "${module}" 2>&1 | tail -n +2)
	echo "${mods[@]}"
}


# :FIXXME: support for all output formats
subcommand_avail() {
	# use this variable in the output functions
	local -a mods=()
	local dir=''
	
	# get number of columns of terminal
gsell's avatar
gsell committed
574
	cols=$(tput cols)
575 576

	output_header() {
gsell's avatar
gsell committed
577
		let i=($cols-${#dir})/2-2
578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622
		printf -- "%0.s-" $(seq 1 $i) 1>&2
		printf -- " %s " "${dir}" 1>&2
		printf -- "%0.s-" $(seq 1 $i) 1>&2
		printf -- "\n" 1>&2
	}

	terse_output() {
		output_header
		for (( i=0; i<${#mods[@]}; i+=2 )); do
			local mod=${mods[i]}
			local release=${mods[i+1]}
			case $release in
				stable )
					out=''
					;;
				* )
					out=${release}
					;;
			esac
			printf "%-20s\t%s\n" "${mod}" "${out}" 1>&2
		done
		echo 1>&2
	}

	long_output() {
		output_header
		for (( i=0; i<${#mods[@]}; i+=2 )); do
			local mod=${mods[i]}
			local release=${mods[i+1]}
			case $release in
				stable )
					out=''
					;;
				* )
					out=${release}
					;;
			esac
			printf "%-20s\t%s\n" "${mod}" "${out}" 1>&2
		done
		echo 1>&2
	}

	human_readable_output() {
		output_header

gsell's avatar
gsell committed
623
		local -i column=$cols
624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641
		local -i colsize=16
		for ((i=0; i<${#mods[@]}; i+=2)); do
			if [[ ${userlvl} == 'novice' ]]; then
			        local  release=${mods[i+1]}
			        case ${mods[i+1]} in
					stable )
						mod=${mods[i]}
						;;
					* )
						mod="${mods[i]}(${release:0:1})"
						;;
				esac
			else
				mod=${mods[i]}
			fi
			local -i len=${#mod}
			local -i span=$(( len / 16 + 1 ))
			local -i colsize=$(( span * 16 ))
gsell's avatar
gsell committed
642
			if (( column+len >= cols )); then
643 644 645
			        printf -- "\n" 1>&2
				column=0
			fi
gsell's avatar
gsell committed
646
			if (( column+colsize < cols )); then
647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671
			        fmt="%-${colsize}s"
			else
				fmt="%-s"
			fi
			printf "${fmt}" "${mod}" 1>&2
			column+=colsize
		done
		printf -- "\n\n" 1>&2
	}

	if [[ $# == 0 ]]; then
	        set -- ''
	fi
	while (( $# > 0 )); do
		local  module=$1
		for dir in "${modulepath[@]}"; do
			mods=( $( get_available_modules "${dir}" "${module}" ) )
			[[ ${#mods[@]} == 0 ]] && continue

			${output_function}
		done
		shift
	done
}

672
get_families () {
673 674
	local -r module_hierarchy_root="$1"
	if [[ ! -d "${module_hierarchy_root}" ]]; then
675 676
		echo ""
	else
677
	{
678
		cd "${module_hierarchy_root}"
679
		ls -1
680
	}
681
	fi
682 683
}

684
#
685 686
# $1: root of modulefile hierarchy
# $2: family name (not path!)
687
compute_family_depth () {
688 689
	local -r module_hierarchy_root="$1"
	local -r family=$2
690
	{
691
		cd "${module_hierarchy_root}"
gsell's avatar
gsell committed
692
		local -r tmp=$(find "${family}" -depth -type f -o -type l | head -1)
693 694 695 696 697 698 699
		local -ar tmp2=( ${tmp//\// } )
		local depth=${#tmp2[@]}
		let depth-=3
		echo ${depth} 
	};
}

700 701 702 703 704 705 706 707 708
subcommand_use() {
	if [[ $# == 0 ]]; then
		local f
		local r
		echo -e "Used families:" 1>&2
		for f in ${used_families//:/ }; do
			echo -e "\t${f}" 1>&2
		done
		echo -e "\nFamilies you may use in addition:" 1>&2
709 710
		for family in $(get_families "${modulepath_root}"); do
			local -i depth=$( compute_family_depth "${modulepath_root}" "${family}")
711 712 713 714
			if ! is_used_family $f && (( depth == 0 )); then
			    echo -e "\t${f}" 1>&2
			fi
		done
715 716 717 718 719 720 721 722
		
		echo -e "\nUsed releases:" 1>&2
		for r in ${used_releases//:/ }; do
			echo -e "\t${r}" 1>&2
		done
		echo -e "\nReleases you may use in addition:" 1>&2
		for r in ${available_releases//:/ }; do
			if ! is_used_release $r; then
723
				echo -e "\t${r}" 1>&2
724 725 726 727 728 729 730 731 732 733
			fi
		done

		echo -e "\nAdditonal directories in MODULEPATH:" 1>&2
		for (( i=0; i<${#modulepath[@]}; i++)); do
			if [[ ! ${modulepath[i]} =~ ${PSI_PREFIX} ]]; then
				echo -e "\t${modulepath[i]}" 1>&2
			fi
		done
	else
734

735 736 737 738 739 740 741 742 743 744 745 746
		local dirs_to_add=()
		local subcommand_switches=''
		while (( $# > 0)); do
			arg=$1
			if [[ ${arg} == -a ]] || [[ ${arg} == --append ]]; then
			        subcommand_switches='--append'
			elif [[ ${arg} == -p ]] || [[ ${arg} == --prepend ]]; then
			        subcommand_switches=''
			elif is_release "${arg}"; then
			        # releases are always *appended*
			        append_path PSI_USED_RELEASES "${arg}"
			elif [[ ! ${arg} =~ */* ]] && [[ -d ${modulepath_root}/${arg} ]]; then
747
				local -i depth=$(compute_family_depth "${modulepath_root}" "${arg}")
748 749 750 751 752 753 754 755 756
				if (( depth == 0 )); then	
			        	dirs_to_add+=( ${modulepath_root}/${arg} )
				else
					echo "${0##_}: cannot add family ${arg} to module path"
					return 3
				fi
			elif [[ ${arg} =~ ^${modulepath_root} ]]; then
				echo "${0##_}: illegal directory: ${arg}" 1>&2
				return 3
757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823
			elif [[ -d ${arg} ]]; then
			        local normalized_dir=$(cd "${arg}" && pwd)
				dirs_to_add+=( ${normalized_dir} )
			elif [[ ${arg} =~ "-*" ]]; then
				echo "${0##_}: illegal switch: ${arg}" 1>&2
				return 3
			else
				echo "${0##_}: neither a directory, release or family: ${arg}" 1>&2
				return 3
			fi
			shift
		done
		echo "export PSI_USED_RELEASES=${PSI_USED_RELEASES}"
		[[ ${#dirs_to_add[@]} == 0 ]] && return

		subcommand_generic1plus use ${subcommand_switches} "${dirs_to_add[@]}"
	fi
}

subcommand_unuse() {
	local dirs_to_remove=()
	while (( $# > 0)); do
		arg=$1
		if is_release "${arg}"; then
			remove_path PSI_USED_RELEASES "${arg}"
		elif [[ ! ${arg} =~ */* ]] &&  [[ -d ${modulepath_root}/${arg} ]]; then
			dirs_to_remove+=( ${modulepath_root}/${arg} )
		elif [[ -d ${arg} ]]; then
			local normalized_dir=$(cd "${arg}" && pwd)
			dirs_to_remove+=( ${normalized_dir} )
		elif [[ ${arg} =~ "-*" ]]; then
		        echo "${0##_}: illegal switch: ${arg}" 1>&2
			return 3
		else
			echo "${0##_}: not a directory: ${arg}" 1>&2
			return 3
		fi
		shift
	done
	echo "export PSI_USED_RELEASES=${PSI_USED_RELEASES}"
	[[ ${#dirs_to_remove[@]} == 0 ]] && return
	subcommand_generic1plus unuse "${dirs_to_remove[@]}"
}

subcommand_update() {
	subcommand_generic0 update "$@"
}

subcommand_refresh() {
	subcommand_generic0 refresh "$@"
}

subcommand_purge() {
	subcommand_generic0 purge "$@"
}

subcommand_list() {
	subcommand_generic0 list "$@"
}

subcommand_clear() {
	subcommand_generic0 clear "$@"
}

subcommand_search() {
	local modules=()
	local with_modules='//'
824
	local src_prefix=''
825
	local _print_header='yes'
826
	local _print_modulefiles='no'
827 828 829 830 831 832 833 834 835 836 837 838 839 840 841
	local use_releases=':'
	local -r fmt="%-20s %-10s %-12s %-s\n"

	# no args
	print_header() {
		printf '\n' 1>&1
		printf "${fmt}" "Module" "Release" "Family" "Requires" 1>&2
		printf -- '-%.0s' {1..60} 1>&2
		printf '\n' 1>&2
	}

	# args:
	# $1: module name pattern
	search () {
		local -r module=$1
842
		local -r module_hierarchy_root="${src_prefix}/${PSI_MODULES_ROOT}"
843 844
		# we must write temporary results to a file for sorting
		local -r tmpfile=$( mktemp /tmp/$(basename $0).XXXXXX ) || exit 1
845
		local family
846
		# loop over all families
847 848
		for family in $(get_families "${module_hierarchy_root}"); do
			local -i depth=$( compute_family_depth "${module_hierarchy_root}" "${family}" )
849 850
			# get all potential directories of family $f with module-files 
			local mpaths=( $(find \
851
					     "${module_hierarchy_root}/${family}" \
852 853 854 855 856 857
					     -type d \
					     -mindepth ${depth} -maxdepth ${depth} \
					     2>/dev/null))
			local mpath
			for mpath in "${mpaths[@]}"; do
				# get dependencies encoded in directory name
858
				local p="${mpath/${module_hierarchy_root}}"
859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878
				p=( ${p//\// } )
				local deps=()
				local -i i
				for ((i=1; i < ${#p[@]}; i+=2)); do
					deps+=( ${p[i]}/${p[i+1]} )
				done
				local requires=${deps[@]}

				# get and print all available modules in $mpath
				# with respect to the requested releases
				local mods=( $( get_available_modules \
						    "${mpath}" \
						    "${module}" \
						    "${use_releases}" ) )
				[[ ${#mods[@]} == 0 ]] && continue
				for (( i=0; i<${#mods[@]}; i+=2 )); do
					printf "${fmt}" ${mods[i]} "${mods[i+1]}" \
					       ${family} "${requires}" >> "${tmpfile}"
				done
			done
879
		done
880
		if [[ "${_print_modulefiles}" == "no" ]]; then
881 882 883
			sort -k 1,1 -k 4,4 -k 5,5 "${tmpfile}" | awk "${with_modules}" 1>&2
		else
			while read -a line; do
884
				echo -n "${line[2]}/" 1>&2
885
				for d in "${line[@]:3}"; do
886
					echo -n "$d/" 1>&2
887
				done
888
				echo "${line[0]}" 1>&2
889 890
			done < <(sort -k 1,1 -k 4,4 -k 5,5 "${tmpfile}" | awk "${with_modules}")
		fi
891 892 893 894 895 896 897 898 899
		rm -f "${tmpfile}"
	}

	
	while (( $# > 0 )); do
		case $1 in
			--no-header )
				_print_header='no'
				;;
900 901 902 903
			--print-modulefiles )
				_print_modulefiles='yes'
				_print_header='no'
				;;
904 905 906
			--release=* )
				_val=${1/--release=}
				if is_release "${_val}"; then
907
				        use_releases+="${_val}:"
908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923
				else
					echo "${_val}: illegal release name." 1>&2
					exit 1
				fi
				;;
			--with=* )
				_arg=${1/--with=}
				if [[ -z ${_arg} ]]; then
				    echo "$1: module missing." 1>&2
				    exit 1
				fi
				with_modules+=" && / ${_arg//\//\\/}/"
				;;
			-a | --all-releases )
				use_releases=${available_releases}
				;;
924 925 926 927
			--src=* )
				src_prefix=${1/--src=}
				check_pmodules_directories "${src_prefix}"
				;;
928 929 930 931 932 933 934 935 936 937 938 939 940
			-? | -h | --help )
				usage
				;;
			-* )
				echo "$1: invalid argument." 1>&2
				exit 1
				;;
			* )
				modules+=( $1 )
				;;
		esac
		shift
	done
941 942 943 944
	if [[ -z "${src_prefix}" ]]; then
	        src_prefix="${PSI_PREFIX}"
	fi
	
945
	if [[ "${use_releases}" == ":" ]]; then
946
                use_releases=":${PSI_USED_RELEASES}:"
947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195
	fi
	
	[[ "${_print_header}" == "yes" ]] && print_header
	if [[ ${#modules[@]} == 0 ]]; then
		modules+=( '' )
	fi
	
	for module in "${modules[@]}"; do
		search "${module}"
	done
}

subcommand_help() {
	if [[ $# == 0 ]]; then
	        usage
	elif typeset -F subcommand_help_$1 > /dev/null 2>&1 ; then
	        # help for sub-command
		subcommand_help_$1
	else
		# :FIXME: print help of newest *available* module
		# (respecting PSI_USED_RELEASES)
		subcommand_generic1plus help "$@"
	fi
}

subcommand_whatis() {
	subcommand_generic0plus whatis "$@"
}

subcommand_apropos() {
	subcommand_generic1 apropos "$@"
}

subcommand_initadd() {
	subcommand_generic1plus initadd "$@"
}

subcommand_initprepend() {
	subcommand_generic1plus initprepend "$@"
}

subcommand_initrm() {
	subcommand_generic1plus initrm "$@"
}

subcommand_initswitch() {
	if [[ $# == 0 ]]; then
	        echo "${subcommand}: missing argument" 1>&2
		return 3
	fi
	if [[ $# > 2 ]]; then
	        echo "${subcommand}: to many arguments" 1>&2
		return 3
	fi
	"${modulecmd}" "${shell}" initswap "$@"
}

subcommand_initlist() {
	subcommand_generic0 initlist "$@"
}

subcommand_initclear() {
	subcommand_generic0 initclear "$@"
}

subcommand_sync() {
	local _srcdir
	local _dstdir
	local _dryrun='no'
	local _delete='no'
	local _args=()
	while (( $# > 0 )); do
		case $1 in
			--from=* )
				_srcdir=${1/--from=}
				_args+=( $1 )
				;;
			--to=* )
				_dstdir=${1/--to=}
				_args+=( $1 )
				;;
			--dry-run )
				_dryrun='yes'
				_args+=( --dryrun )
				;;
			--delete )
				_delete='yes'
				_args+=( $1 )
				;;
			* )
				echo "$1: invalid argument." 1>&2
				exit 1
				;;
		esac
		shift
	done
	${PMODULES_HOME}/bin/modsync.bash "${_args[@]}"
}

case $1 in
	bash )
		declare shell=$1
		;;
	* )
		echo "$1: unsupported shell" 1>&2
		exit 1
		;;
esac
shift

while (( $# > 0 )); do
	case $1 in
		-h | -H | -\? | --help | -help )
			usage
			exit 1
			;;
		-V | --version )
			print_version
			exit 1
			;;
		-f | --force )
			# ignored
			;;
		-t | --terse )
			output_function='terse_output'
			;;
		-l | --long )
			output_function='long_output'
			;;
		--human )
			output_function='human_readable_output'
			;;
		--versbose )
			verbosity='verbose'
			;;
		--silent )
			verbosity='silent'
			;;
		-c | --create )
			sw_create='yes'
			;;
		-i | --icase )
			# ignored
			;;
		-u | --userlvl )
			case $2 in
				nov | novi | novic | novice )
					userlvl='novice'
					;;
				exp | expe | exper | expert )
					userlvl='expert'
					;;
				adv | adva | advan | advanc | advance | advanced )
					userlvl='advanced'
					;;
				* )
					echo "$1: unknown user level" 1>&2
					exit 1
					;;
			esac
			shift
			;;
		-* )
			echo "$1: unknown switch.\n" 1>&2
			exit 1
			;;
		add|load )
			subcommand='subcommand_load'
			shift
			sargs=( $* )
			shift $#
			;;
		rm|unload )
			subcommand='subcommand_unload'
			shift
			sargs=( $* )
			shift $#
			;;
		switch|swap )
			subcommand='subcommand_swap'
			shift
			sargs=( $* )
			shift $#
			;;
		display|show )
			subcommand='subcommand_show'
			shift
			sargs=( $* )
			shift $#
			;;
		apropos|keyword )
			subcommand='subcommand_apropos'
			shift
			sargs=( $* )
			shift $#
			;;
		avail|search|use|unuse|update|refresh|purge|list|clear|whatis|help )
			subcommand=subcommand_$1
			shift
			sargs=( $* )
			shift $#
			;;
		initadd|initprepend|initrm|initswitch|initlist|initclear )
			subcommand=subcommand_$1
			shift
			sargs=( $* )
			shift $#
			;;
		sync )
			subcommand=subcommand_$1
			shift
			sargs=( $* )
			shift $#
			;;
		* )
			echo "$1: unknown sub-command" 1>&2
			exit 1
	esac
	shift
done

#for ((i=0; i<$#; i++)); do
#	case "${sargs[i]}" in
#		-a | --append )
#			if [[ ${subcommand} != use ]]; then
#			        echo "${subcommand}: unsupported switch '$1'" 1>&2
#				exit 1
#			fi
#			;;
#		-* )
#			echo "${subcommand}: unsupported switch '$1'" 1>&2
#			exit 1
#			;;
#		[a-zA-Z0-9] )
#			:
#			;;
#		* )
#			echo "$1: illegal module name" 1>&2
#			;;
#	esac
#done

$subcommand "${sargs[@]}"

# Local Variables:
# mode: sh
# sh-basic-offset: 8
# tab-width: 8
# End: