#!/bin/sh

LANG=C ; export LANG
LC_ALL=C ; export LC_ALL

case `pwd` in
    */gdb ) ;;
    * )
	echo "Must be in gdb directory" 1>&2
	exit 1
esac

# Word wrap the output

wordwrap ()
{
    awk '
BEGIN {
}
/^\t/ { print; next }
NF > 0 {
    linelength = 77
    line = $1
    i = 2
    do {
	while (length (line " " $i) < linelength && i <= NF) {
	    line = line " " $i
	    i++
	}
	if (i <= NF) {
	    print line " \\"
	    line = "\t" $i
	    i++
	    linelength = 70
	} else {
	    print line
	    break
	}
    } while (1)
}
'
}


# Generate a list of includes with the file names munged into
# $(name_h) form.

generate_includes ()
{
    sed -n '
/^#[^"]*include[^"]*"[^"]*"/ {
    s,^[^"]*"\([^"]*\)".*$,\1,
    s,[-\./],_,g
    s,^\([a-z]*_\)\1,\1,
    s,\(.*\), $(\1),
    H
}
/^#[^"]*include[^A-Z_<"]*[A-Z_][A-Z_]*/ {
    s,^[^A-Z_<"]*\([A-Z_][A-Z_]*\).*$,\1,
    s,[-\./],_,g
    s,^\([a-z]*_\)\1,\1,
    s,\(.*\), $(\1),
    H
}
$ {
    x
    s,\n,,g
    p
}' $1
}

# Generate a header dependency list

generate_h ()
{
    lhs=`echo $1 | sed \
	    -e 's/\.l$/.c/' \
	    -e 's,[-\./],_,g' \
	    -e 's,^\([a-z]*_\)\1,\1,' \
	    -e 's,^\([a-z]*\)_\1,\1,' \
	    `
    rhs=`generate_includes $1`
    case $1 in
	*/*) s="\$(srcdir)/$1" ;;
	*) s="$1" ;;
    esac
    s="`echo ${s} | sed -e 's/\.l$/.c/'`"
    echo ${lhs} = ${s} ${rhs}
}

# Iterate through the .h files generating a list of files each
# includes.

rm -f Makefile.h.in
for d in "" cli/ mi/ tui/ signals/
do
    # Generate the dependencies
    ls ${d}*.h ${d}*.l 2>/dev/null | sort -d | while read f
    do
	case "${f}" in
	    acconfig.h ) ;;
	    new-gdbarch.[ch] ) ;;
	    * ) generate_h ${f} ;;
	esac
    done | wordwrap > Makefile.h.in
    # Insert the dependencies
    if test -s Makefile.h.in
    then
	start="# gdb/$d headers"
	match=`echo "${start}" | sed -e 's,/,\\\\/,g'`
	ed Makefile.in <<EOF
/${match}/
/^$/;/^#/-1 d
i

.
. r Makefile.h.in
p
a

.
w
q
EOF
    fi
done


# Generate a .c dependency list

generate_c ()
{
    case $1 in
	*/*) s="\$(srcdir)/$1" ;;
	*) s=$1 ;;
    esac
    imp=`echo $s | sed \
	    -e 's/\.[cly]$/.c/'`
    if head -1 $1 | grep OBSOLETE > /dev/null 2>&1
    then
	echo -n "# OBSOLETE "
    fi
    lhs=`echo $1 | sed \
	    -e 's/\.[cly]$/.o/' \
	    -e 's,^.*/,,'`
    rhs=`generate_includes $1`
    echo ${lhs}: ${imp} ${rhs}
    case $1 in
	*/*) printf '\t$(CC) -c $(INTERNAL_CFLAGS) $(srcdir)/%s\n' "$1" ;;
    esac
}

# Iterate through the .c files updating the dependencies

for d in "" cli/ mi/ tui/ signals/
do
    # Generate the dependencies
    ls ${d}*.c ${d}*.y 2>/dev/null | sort -d | while read f
    do
	case "${f}" in
	    new-gdbarch.[ch] ) ;;
	    * ) generate_c $f ;;
	esac
    done | wordwrap > Makefile.c.in
    # Insert the dependencies
    if test -s Makefile.c.in
    then
	start="# gdb/$d dependencies"
	match=`echo "${start}" | sed -e 's,/,\\\\/,g'`
	ed Makefile.in <<EOF
/${match}/
/^$/;/^#$/-1 d
i

.
. r Makefile.c.in
p
a

.
w
q
EOF
    fi
done
