#!/bin/bash

set -e -u

VERBOSE=false
LIST_OPTS=false

usage()
{
	echo "
usage: $0 [options]

options:
 -v	verbose
 -a	list optional modules also (app-*, dev-*, x-*)
" >&2
	exit 1
}

while [ $# != 0 ]
do
  case $1 in
    -v|--verbose)	VERBOSE=true ;;
    -a|--all)		LIST_OPTS=true ;;
    *)			usage ;;
  esac
  shift
done


modules=$( (
		ls | egrep -v '^[A-Z]|\.sh$|builtin-'
		ls -d [A-Z]*/* | sed -e 's#.*/##'
	) | egrep -v '\.sh$|^builtin-|^model-|^local-'
)
$LIST_OPTS || modules=$(echo "$modules" | egrep -v '^app-|^dev-|^x-')

modules=$(echo "$modules" | sort -u)

by_conf=$(
	$VERBOSE && echo "searching configs ..." >&2
	mods=$(for class in $(kusa-conf --list class.)
	do
		kusa-conf ${class}.modules 2>/dev/null
	done)
	echo $mods | sed -e "s/ /\n/g" | sort -u
)
required=$(
	$VERBOSE && echo "searching required ..." >&2
	for file in $(find * -name requires -o -name requires_post)
	do
		cat $file
	done | sort -u
)


for mod in $modules
do
	echo "$by_conf" | grep -q "^$mod$" && {
		$VERBOSE && echo " by_conf  $mod"
		continue
	}
	echo "$required" | grep -q "$mod$" && {
		$VERBOSE && echo " required $mod"
		continue
	}
	if $VERBOSE
	then
		echo " NONE     $mod"
	else
		echo "$mod"
	fi
done

exit 0
