#!/bin/sh
#
# A script for building an executable from the common runtime, modules and
# libraries.
#
# Usage:
#
usage="llld name floatingp cpp_link_p target_dir rtname rt_dir {objname src_dir}* [ -s {name src_dir}* ] [ -l {option}* ] [ -user-main ]"

if [ $# -lt 6 ]
then
  echo $usage
  exit 1
fi

name=$1
floatingp=$2
cpplinkp=$3
tdir=$4
rtname=$5
rtdir=$6

shift;shift;shift;shift;shift;shift

objects=""

while [ $# != 0 -a "x$1" != "x-s" -a "x$1" != "x-l" -a "x$1" != "x-user-main" ]
do
  objects="$objects $2/$1.o"
  shift;shift
done

shared=""


if [ "x$1" = "x-s" ]
then
  shift
  while [ $# != 0 -a "x$1" != "x-l" -a "x$1" != "x-user-main" ]
  do
     if [ "$floatingp" = "yes" ]
     then
       shared="$shared -L$2 -l`echo $1 | cut -c4-`"
     else
       shared="$shared $2/$1.so.1.0"
     fi
     shift;shift
  done
fi

options=""

if [ "x$1" = "x-l" ]
then
  shift
  while [ $# != 0 -a "x$1" != "x-user-main" ]
  do
     options="$options $1"
     shift
  done
fi

usermain=no

if [ "x$1" = "x-user-main" ]
then
  shift
  usermain=yes
fi

if [ $# != 0 ]
then
  echo $usage >&2
  exit 1
fi

if [ "$floatingp" = "yes" ]
then
  rtshared="-L$rtdir -l`echo $rtname | cut -c4-`"
else
  rtshared="$rtdir/$rtname.so.1.0"
fi

llstanda=$ILT_DIR/talk/common/llstanda.c

rm -f $tdir/$name

include="-I$ILT_DIR/talk/common -I$ILT_DIR/talk/i86_linux1.2_gnu2.7"

if [ "$cpplinkp" = "yes" ]
then
  cmd="g++ $include  -O -g"
else
  cmd="gcc $include  -O -g"
fi

allobjects="$rtshared $objects $shared"

# Build up list of directories for LD_LIBRARY_PATH.
shlibdirs=""
for o in $allobjects $options
do
  case "$o" in
    -L*) shlibdir=`echo "x$o" | sed -e 's,^x-L,,'`
         case ":${shlibdirs}" in
           *":${shlibdir}:"* ) ;;
           * )               shlibdirs="${shlibdirs}${shlibdir}:" ;;
         esac
         ;;
  esac
done
rm -f $tdir/$name.libpath
if test -n "$shlibdirs" ; then
  (echo "# For execution of $name, LD_LIBRARY_PATH needs to include some directories."
   echo "# From within sh or ksh or bash, executing  . $name.libpath"
   echo "# will add these directories to your LD_LIBRARY_PATH."
   echo
   echo "LD_LIBRARY_PATH=$shlibdirs"'${LD_LIBRARY_PATH-"/lib:/usr/lib"}'
   echo "export LD_LIBRARY_PATH" ) > $tdir/$name.libpath
fi

if [ $usermain = yes ]
then
  echo $cmd \$1 \\ > $tdir/$name
  for o in $allobjects
  do
    echo "   " $o \\ >> $tdir/$name
  done
  echo "   " -lm -lieee -ldl $options -o \`dirname \$0\`/\`echo \$1 \| sed -e \"s%.*/%%\" -e \"s%\\\.[cC][cCpP+]*\$%%\"\` >> $tdir/$name
  chmod +x $tdir/$name
else
  $cmd $llstanda $allobjects -lm -lieee -ldl \
	$options -o $tdir/$name
  status=$?
  rm -f llstanda.o
  test $status = 0 || exit $status
  # Check that all the symbols needed in the executable are resolved.
  if test -n "`ldd -r $tdir/$name 2>&1 > /dev/null`"; then
    ldd -r $tdir/$name
    mv $tdir/$name $tdir/$name.$$
    exit 1
  fi
  exit 0
fi

