#!/usr/bin/bash
MAKEFILE='Makefile'
while [[ ! -f "${MAKEFILE}" ]]; do
	MAKEFILE=../"${MAKEFILE}"
done

FIND="find . -maxdepth 1 '(' -name '*.md' -o -name '*.tex' ')' -a -not -name 'Aufgabe[0-9].tex' -a -not -name '_*'"

if [[ ! -f "${MAKEFILE}" ]]; then
	echo "No root Makefile found" >&2
	exit 1
fi

targets=( "$@" )
if [[ -z "${targets[*]}" ]]; then
	# Autodetect targets
	mapfile -t sources < <(eval "${FIND}")
	for source in "${sources[@]}"; do
		declare -a new_targets=()
		case "$(basename "${source}")" in
		slides.md)
			new_targets+=("slides.pdf" "slides.pptx")
			;;
		*)
			mapfile -t new_targets < <(echo "${source}" | sed -e 's/\.tex$/.pdf/g' -e 's/\.md$/.pdf/g')
			;;
		esac

		if [[ "${source}" != *"test_lehrer.tex" ]] \
		&& [[ "${source}" != *"test_loesung.tex" ]] \
		&& grep -qe 'iflehrer\|lehrerversion\|gap\|solution' "${source}"; then
			declare -a sus_targets=( "${new_targets[@]}" )
			for sus_target in "${sus_targets[@]}"; do
				dir=$(dirname "${sus_target}")
				target_file=$(basename "${sus_target}")
				new_targets+=("${dir}/lehrer_${target_file}")
			done
		fi
		targets+=( "${new_targets[@]}" )
	done
fi

exec make -f "${MAKEFILE}" "${targets[@]}"

