#!/bin/sh

# pydist.sh: a reference-only, development-time script
# objective: generate pydist.mk based on the scripts found
#            under $PYTHON_SRCDIR/Lib, excluding the 'test'
#            and 'plat-*' sub-directories.

printf 'PYCOPY        = $(PROJECT_DIR)/project/pycopy.sh\n'
printf 'PYCOPY_PYTHON = $(NICKNAME)\n'
printf 'PYCOPY_PREFIX = $(PREFIX)\n\n'

printf 'PYDIST_LIBDIR = lib\n'
printf 'PYDIST_PYCDIR = lib/$(NICKNAME)\n\n\n'

printf 'PYDIST_SYSCFG_SRCS = \\\n'
printf '\t$(PYDIST_PYCDIR)/./_sysconfigdata.py\n\n'

cd "$PYTHON_SRCDIR"/Lib || exit 2

pydirs=$(find . -type d | grep -v -e '^\./test' -e '^./plat-' | sort)

for pydir in $pydirs; do
	if [ $(find "$pydir" -name '*.py' | wc -l) != '0' ]; then
		pyvar=$(printf "PYDIST_%s_SRCS" $pydir \
			| sed -e 's@\_\.@@g' -e 's@/@_@g' -e 's@-@_@g' \
			| tr "[:lower:]" "[:upper:]")

		printf "%s = "'\\'"\n" "$pyvar"
		pyvars="$pyvars $pyvar"

		for pysrc in $pydir/*.py; do
			if [ $pysrc != $pydir/py3_test_grammar.py ]; then
				printf "\t"'$(PYDIST_PYCDIR)/'"%s "'\\'"\n" $pysrc
			fi
		done | sort;

		echo
	fi
done

printf '\n\n'
printf 'pydist.tag:\n'

for pydir in $pydirs; do
	if [ $pydir != '.' ]; then
		printf '\tmkdir -p $(PYDIST_PYCDIR)/%s\n' $pydir
	fi
done

printf '\ttouch pydist.tag\n'
printf '\n\n'

for pydir in $pydirs; do
	pyrule=$(printf '$(PYDIST_PYCDIR)/'"%s/%s.py:" "$pydir" '%')
	printf "%-64s"'$(SOURCE_DIR)/Lib/'"%s/%s.py"' pydist.tag\n' "$pyrule" "$pydir" '%'

	pyrule_python=$(printf "\t\t"'PYCOPY_PYTHON=$(PYCOPY_PYTHON)')
	pyrule_prefix=$(printf "\t\t"'PYCOPY_PREFIX=$(PYCOPY_PREFIX)')
	pyrule_dstdir=$(printf "\t\t"'PYCOPY_DSTDIR=$(PYDIST_PYCDIR)/'"%s" "$pydir")

	printf "%s"' \\\n' "$pyrule_python"
	printf "%s"' \\\n' "$pyrule_prefix"
	printf "%s"' \\\n' "$pyrule_dstdir"
	printf '\t\t$(PYCOPY) $<\n\n'
done

printf 'PYDIST_PY_SRCS = \\\n'

for pyvar in PYDIST_SYSCFG_SRCS $pyvars; do
	printf "\t"'$('"%s"') \\\n' $pyvar
done

printf '\n\n'
printf 'pydist-py-srcs:\t$(PYDIST_PY_SRCS)\n\n'
printf 'pydist-py-srcs-clean:\n'
printf '\trm -f $(PYDIST_PY_SRCS)\n'
printf '\trm -f pydist.tag\n\n'
printf 'clean:\tpydist-py-srcs-clean\n\n'

printf '.PHONY:\tpydist-py-srcs\n'
printf '.PHONY:\tpydist-py-srcs-clean\n\n'

exit 0
