#! /bin/bash

in_modules_root="$1"
out_modules_root="$2"
shift; shift

modules="$@"

mkdir -p "${out_modules_root}" 2>/dev/null >/dev/null
in_modules_root="$(cd "${in_modules_root}" || exit 1; pwd 2>/dev/null)"
out_modules_root="$(cd "${out_modules_root}" || exit 1; pwd 2>/dev/null)"

if [ -z "${in_modules_root}" -o -z "${out_modules_root}" ]; then
	echo "Usage: generate_modules_dir <in_dir> <out_dir> <modules>" >&2

	exit 1
fi

cd "${in_modules_root}" || exit 1

modules="$(for module in $(echo ${modules}); do
	if [ ! -f "${module}" ]; then
		continue
	fi

	readlink -f "${module}" | sed 's@^'"${in_modules_root}"'/@@'
done)"

for try in {1..100}; do
	changed='0'
	for module in ${modules}; do
		module_re="$(echo "${module}" | sed 's@\.@\.@g')"

		module_deps="$(grep "^${module_re}:" modules.dep | cut -f 2- -d :)"
		for module_dep in ${module_deps}; do

			module_dep_re="$(echo "${module_dep}" | sed 's@\.@\.@g')"
			if echo "${modules}" | grep "^${module_dep_re}$" >/dev/null; then
				continue
			fi

			echo "Adding ${module_dep} (for ${module})"
			modules="${module_dep}
${modules}"


			changed='1'
		done
	done

	if [ "${changed}" = '0' ]; then
		break
	fi
done

for module in ${modules}; do
	out_module_dir="${out_modules_root}/$(dirname "${module}")"

	mkdir -p "${out_module_dir}"
	cp "${module}" "${out_module_dir}"
done
