#!/bin/bash
# 
# given a Module.supported, Module.base and modules.dep, generate list
# of base / supported / unsupported modules

set -e
export LC_COLLATE=C

usage()
{
	echo "Usage: ${0##*/} -b Module.base -s Module.supported [-d dir] [-i] [-o outdir]"
}

options=$(getopt -o b:s:d:o:i -- "$@")
if test $? -ne 0; then
	usage >&2
	exit 1
fi
eval set -- "$options"
opt_base=
opt_supp=
opt_out=.
opt_dir=.
opt_ignore_errors=false
while test $# -gt 0; do
	opt=$1
	shift
	case "$opt" in
	-b | -s | -d | -o | -D)
		arg=$1
		shift
	esac
	case "$opt" in
	-b)
		opt_base=$arg ;;
	-s)
		opt_supp=$arg ;;
	-d)
		opt_dir=$arg ;;
	-o)
		opt_out=$arg ;;
	-i)
		opt_ignore_errors=true ;;
	--)
		break ;;
	*)
		echo "Unknown option $opt" >&2
		exit 1
	esac
done
if test -z "$opt_base" -o -z "$opt_supp"; then
	usage >&2
	exit 1
fi

trap 'rm -rf "$tmp"' EXIT
tmp=$(mktemp -d)
mkdir "$tmp/empty"

find "$opt_dir" -type f -name '*.ko' -printf '/%P\n' | \
	awk -F/ '{ n=$NF; gsub(/-/, "_", n); sub(/\.ko$/, "", n); print n " " $0; }' | \
	sort >"$tmp/all"

modules_dep=$(find "$opt_dir" -type f -name modules.dep)
if test -z "$modules_dep"; then
	echo "Cannot find modules.dep in $opt_dir" >&2
	exit 1
fi
(
	echo '%:
	@echo $@
ifdef EXPLAIN
	@for dep in $^; do echo "$$dep needed by $@"; done >> $(EXPLAIN)
endif
'
	sed -r 's:[^ ]*/([^/]*)\.ko\>:\1:g; y/-/_/' "$modules_dep"
) >"$tmp/dep"

add_dependent_modules()
{
	xargs -r make EXPLAIN=$1 -rRs -C "$tmp/empty" -f "$tmp/dep" | sort -u
}

# base
sed 'y/-/_/' <"$opt_base" | add_dependent_modules >"$tmp/base"
join -j 1 -o 2.2 "$tmp/base" "$tmp/all" >"$opt_out/base-modules"

# main
sed 's/ .*//; y/-/_/' "$opt_supp" | sort -u >"$tmp/supp"
add_dependent_modules "$tmp/supp-explain" <"$tmp/supp" >"$tmp/supp-all"
if ! cmp -s "$tmp/supp" "$tmp/supp-all"; then
	echo "The following unsupported modules are used by supported modules:" >&2
	join -j1 -a2 <(sort "$tmp/supp-explain") \
		 <(join -v2 "$tmp/supp" "$tmp/supp-all") >&2
	echo "Please fix supported.conf." >&2
	if ! $opt_ignore_errors; then
		exit 1
	fi
fi
join -j 1 -o 2.2 "$tmp/supp-all" "$tmp/all" >"$opt_out/main-modules"

# unsupported
join -j 1 -v 2 -o 2.2 "$tmp/supp-all" "$tmp/all" >"$opt_out/unsupported-modules"

exit 0


