#! /bin/sh

# This script generates a list of the subdirectories of the current
# directory according to the following:
# 
# 	1. any subdirectory named RCS is excluded from the list;
# 	2. if there is a file called EXCLUDEDIRS in the current
# 	   directory, any directories whose names are listed
# 	   in that file are excluded.
#	3. if there is a file called FIRSTDIRS in the current
#	   directory, any directories whose names are listed
#	   in that directory are listed first in the list,
#	   in the order they appear in the file.
# 
# The resulting list is echoed on a single line to stdout.

case "$1" in
  srcfor)		# DIRS_THIS_MACH_NO_OBJ
    choose="
     O.*) test ;;
       *) test -d \$file/O.$2 || (test \"\$file/O.*\" = \"\`echo \$file/O.*\`\");" ;;

  src)			# DIRS_NO_OBJ
    choose="O.*) test ;;  *) :" ;;

  ""|all)		# DIRS
    choose="*) :" ;;

  *)			# DIRS_THIS_MACH
    choose="
	O.$1) : ;;
	O.*) test ;;
	*) test -d \$file/O.$1  || (test \"\$file/O.*\" = \"\`echo \$file/O.*\`\")" ;;
esac

exceptions="RCS"

if [ -r EXCLUDEDIRS ]; then
  # Make |-separated list of excluded directories, plus RCS
  exceptions="`tr -s '\\12\\11\\40' '|||' <EXCLUDEDIRS`RCS"
  # Sigh, in case EXCLUDEDIRS is just a blank line...
  case "$exceptions" in
    "|"*) exceptions="''$exceptions" ;;
  esac
fi

firstdirs=""
if [ -r FIRSTDIRS ] ; then
  firstdirs="`cat FIRSTDIRS`" ;
  exceptions="`echo $firstdirs $exceptions | tr -s '\\12\\11\\40|' '||||'`''"
  result="$firstdirs"
fi

# Construct a test command, which is fed only directories containing a Makefile.
# If the file is on our list of exceptions, forget it;
# if it's accepted by the "$choose" command above, accept it;
# reject anything else.
candidate="case \$file in ${exceptions}) test ;;  $choose ;;  *) test ;; esac"

for file in *; do
 if [ -d $file -a -r $file/Makefile ] && eval "$candidate"; then
    result="$result $file"
 fi
done

echo $result
