#!/bin/sh

# dist-test-cases --- Generate Makefile.am and fragments of autoconf ac file for Units and Tmain dir
#
# COPYRIGHT NOTICE SHOULD BE HERE
#

#
# Originally this file generates just one file with much "EXTRA_DISTS += " lines.
# However, now we have so many test releates files, EXTRA_DISTS becomes too long
# to pass it to execve.
# See http://gnu-automake.7480.n7.nabble.com/argument-list-too-long-in-project-with-many-files-td21323.html
#
# This second version generates multiple Makefile.am files to make each EXTRA_DISTS in the Makefile.am
# short.
#
print_am_header()
{
    echo "# -*- makefile -*-"
    echo "# Generated by $0"
    echo
}

print_m4_header()
{
    local top=$1

    echo "dnl -*- autoconf -*-"
    echo "dnl Generated by $0"
    echo
    echo 'AC_CONFIG_FILES(['"$top"/Makefile'])'
}

make_am_sub_with_git ()
{
    local d=$1
    local f

    print_am_header
    echo "EXTRA_DIST    ="

    for f in $(git ls-files | sed -n -e 's|^'"$d"'/\(.\+\)|\1|p' | uniq); do
	echo "EXTRA_DIST   +=" "$f"
    done

}

make_am_with_git ()
{
    local top=$1
    local d

    print_am_header
    echo "DIST_SUBDIRS  ="
    echo "EXTRA_DIST    ="
    echo

    for d in $(git ls-files | grep $top | sed -n -e 's|^\(^'$top'/[^/]\+\)\(/.*\)\?|\1|p'  | sort | uniq); do
	if [ -d "$d" ]; then
	    echo "DIST_SUBDIRS +=" $(basename "$d")
	    make_am_sub_with_git $d > $d/Makefile.am
	    echo 'AC_CONFIG_FILES(['$d'/Makefile])' >> $top/dist.m4
	else
	    echo "EXTRA_DIST   +=" $(basename "$d")
	fi
    done
}

rm -f Tmain/dist.m4
print_m4_header Tmain >> Tmain/dist.m4
make_am_with_git Tmain > Tmain/Makefile.am

rm -f Units/dist.m4
print_m4_header Units >> Units/dist.m4
make_am_with_git Units > Units/Makefile.am
