# $Id: inst-all-templ,v 1.5 2000/07/24 21:27:04 carlo Exp $
#
# Script that generates files with template instantiations.
#
# Copyright (C) 1999-2000, by
#
#   Carlo Wood, Run on IRC <carlo@alinoe.com>
#   RSA-1024 0x624ACAD5 1997-01-26                    Sign & Encrypt
#   Fingerprint16 = 32 EC A7 B6 AC DB 65 A6  F6 F6 55 DD 1C DC FF 61
#
# All rights reserved.
#
# See the file LICENSE for copyright information.
#
# This file may be distributed under the terms of the Q Public License 1.0
# as defined by Troll Tech AS of Norway and appearing in the file LICENSE.QPL
# included in the packaging of this file.
#
#-----------------------------------------------------------------------------

# APPDIR should be the directory of the application that needs to be
# analysed.  It must contain a Makefile with the target '$1'.

# APPDIR_OBJS should be a list of objects files, in which the undefined
# references can be found.  Any 'undefined reference' for either a
# template function or template class that is occurs during linking
# causes an template instantiation to be added to the file <name>.tig
# where <name> is the first part of the object file <name>.o with the
# most undefined references in it.  If the file <name>.cc does not
# contain a line "#include "<name>.tig", then this line is added at
# the bottom of that file.

if [ -z "$APPDIR" ]; then
  echo "APPDIR is empty"
  exit -1
fi
if [ -z "$APPDIR_OBJS" ]; then
  echo "APPDIR_OBJS is empty"
  exit -1
fi
if [ "$1" = "build" ]; then
  echo "Building application..."
else
  echo "Building $1..."
fi
(cd "$APPDIR" || exit -1; $(MAKE) $1 2>&1) | tee $1.log
cat $1.log | grep 'undefined reference' |
    awk '{ protodir=ENVIRON["PROTODIR"]; printf("%s/templ-inst/inst-templ %c%s\n", protodir, 39, $$0) }' > tmpfile || exit -1
chmod 700 tmpfile
echo -n > nm_out
for i in $APPDIR_OBJS; do
  echo $i  >> nm_out
  nm -C $i >> nm_out || exit -1
done
./tmpfile | tee log
BASENAMES=`echo "$APPDIR_OBJS" | sed -e 's/\.o$//' -e 's/\.o / /g'`;
for i in $BASENAMES; do
  if [ -e "$i.tig" ]; then
    mv $i.tig $i.tig.bak || exit -1;
    sort $i.tig.bak | uniq > $i.tig || exit -1;
    if diff $i.tig $i.tig.bak > /dev/null;  then
      mv $i.tig.bak $i.tig
    else
      rm $i.tig.bak;
    fi
  fi
done
grep '^Appending: ' log > tmpfile2
if [ -s tmpfile2 ]; then
  rm -f tmpfile2
  exec $PROTODIR/templ-inst/inst-all-templ $1
else
  rm -f tmpfile2
  if [ -e log -a ! -s log ]; then
    $(MAKE) templ-inst-clean
    (cd "$APPDIR" || exit -1; $(MAKE) depend)
  fi
fi
