#! /bin/bash

# This program wants to recieve a list of needed headers on stdin. It
# reads Makefile.am.in and creates Makefile.am.

rethink=no
options=''

while true; do
    case $1 in
    	--rethink)
    	    rethink=yes
    	    ;;
    	--*)
    	    echo make_am: Unknown option $1
    	    exit 1
    	    ;;
	*)
	    break
    esac

    options="$options $1"
    shift
done

if [ $# != 0 ]; then
    dir=$1
    top=no
else
    dir=.
    top=yes
fi

function werror {
    echo 1>&2 "$@"
}

echo 1>&2 "make_am: dir='$dir'"

# Input file on fd 3
if [ -f $dir/Makefile.am.in ]; then
    exec 3<$dir/Makefile.am.in
else
#    echo 1>&2 "make_am: No Makefile.am.in in $dir"
    exit 0
fi

# Output file on fd 4
exec 4>$dir/Makefile.am
echo 1>&4 '##' "Automatically generated by make_am, `date`"
echo 1>&4 '##' "Process this file with automake to produce Makefile.in"
echo 1>&4

function get_header() {
    keyword=''
    while [ x$keyword = x ]; do
	read <&3 keyword args
	if [ $? != 0 ]; then
	    echo 1>&2 "make_am: Unexpected end of file"
	    exit 1
	fi
	case $keyword in
            \#*)
                keyword=''
                ;;
	    *:)
		keyword=`echo $keyword | sed 's/^\(.*\):$/\1/'`
		;;
        esac ;
    done
    echo "get_header: '$keyword'"
}

# Run commands with the same data on stdin
commands=""

function add_command {
    commands="$commands tee >($1 ; cat >/dev/null) |"
}

function run_commands {
    echo 1>&2 "run_commands: $commands cat >/dev/null"
    /bin/bash -c "$commands cat >/dev/null"
}

subdirs=''

while true; do
    get_header;
    case $keyword in
	CVS_HEADERS)
	    # automake expands "foo \\\n\nbar" -> "foo \\\nbar". So
	    # put all the files on one line, for simplicity.  
	    
	    # comm -12 - <(./cvs_headers $dir) | sed 's/\$/ \\\\/';
	    if [ $rethink = yes ]; then
		add_command "(echo $args = .dist_headers\\\\;
		comm -12 - <(./cvs_headers $dir) \\
		     | tee $dir/.dist_headers | tr '\\n' ' ';
		echo) 1>&4"
		
	    else
		(echo $args = .dist_headers \\
		 tr <$dir/.dist_headers '\n' ' '
		 echo) 1>&4
	    fi
	    ;;
	CLASS_FILES)
	    (   echo $args = .dist_classes \\;
		if [ $rethink = yes ]; then
		    ./used_headers .x $dir | tee $dir/.dist_classes \
		                           | tr '\n' ' '
		else
		    tr <$dir/.dist_classes '\n' ' '
		fi
	        echo) 1>&4
	    ;;
	SUBDIRS)
	    subdirs=$args
	    echo 1>&4 "SUBDIRS = $args"
	    for d in $args; do
		add_command "$0 $options $dir/$d"
	    done
	    ;;
	BODY)
	    if [ $top = yes ]; then
		if [ $rethink = yes ]; then
		    ./used_headers .h . $subdirs | run_commands		    
		else
		    run_commands </dev/null
		fi
	    else
		run_commands
	    fi && cat <&3 >&4
	    exit 0
	    ;;
	*)
	    echo 1>&2 "make_am: Unknown keyword '$keyword'"
	    exit 1
	    ;;
    esac
done
