#!/bin/sh

#set -x

LIBSRC=$1
shift
SHAREDLIB=$1
shift
STARTING_ADDRESS=$1
shift
DATA_ADDRESS=$1
shift
SYSLIBS=$1
shift
SHLIB_SYMBOL=$1
shift
STATICLIBDIR=$1
shift
GLOBAL_DATAS=$1
shift
IOSTREAM_OBJS=$1
shift
LIBRARY=$1
SHORTNAME=lib$LIBRARY

SHAREDLIBDIR=${STATICLIBDIR}/shared

AUXLIBDIR=/usr/lib/shlib/jump
# for libresolve
LIBFOO=../libfoo.a
#
ar=${AR-/usr/bin/ar}
cc=${CC-/usr/bin/gcc}
nm="${NM-/usr/bin/nm} -d"
ld=${LD-/usr/bin/ld}
strip=${STRIP-/usr/bin/strip}
ranlib=${RANLIB-/usr/bin/ranlib}
libresolve=${LIBRESOLVE-/usr/bin/libresolve}

jumptable=${JUMPTABLE-no}

/bin/rm -rf sharedlib staticlib
mkdir staticlib

cd staticlib
# get all those .o's
/bin/rm -f __bar __foobar __bar.a __foobar.a
foo=1
for i in $LIBSRC; 
do
  $ar x ../../$i; 

  for f in $GLOBAL_DATAS
  do
    if [ -f $f ]; then
      /bin/rm -f $f
    fi
  done

  echo build the relocation image $i of $SHAREDLIB.
  if [ $foo = 1 ]; then
    $ld -r -o __bar.a *.o
    if [ $? != 0 ]
    then
      echo Failed to build the relocation image $i of $SHAREDLIB.
      exit 1
    fi
    foo=2
  else
    $ld -r -o __bar.a __foobar.a *.o
    if [ $? != 0 ]
    then
      echo Failed to build the relocation image $i of $SHAREDLIB.
      exit 1
    fi
  fi
  mv __bar.a __foobar.a
  /bin/rm -f *.o

done

# build the shared image
echo build the shared image $SHAREDLIB

for i in $GLOBAL_DATAS; 
do
  cp ../../$i .
done
$ld -nostdlib -x -Ttext $STARTING_ADDRESS -Tdata $DATA_ADDRESS \
	 -o ../$SHAREDLIB ../$LIBRARY/$SHORTNAME.jump.o \
	$GLOBAL_DATAS __foobar.a -L$AUXLIBDIR $SYSLIBS

if [ $? != 0 ]
then
  echo Failed to resolve the variables.
  exit 1
fi

#exit 0

cd ..
/bin/rm -fr staticlib

# get all the addresses
mkdir sharedlib
cd ./sharedlib

$nm ../$SHAREDLIB > ../nmshared

case $jumptable in
yes)
  if [ -f ../../stub/$SHORTNAME.nm ]; then
    mv ../../stub/$SHORTNAME.nm ../../stub/$SHORTNAME.nm.old
  fi
  mv ../nmshared ../../stub/$SHORTNAME.nm
  cp ../../stub/$SHORTNAME.stub.nm ../nmshared
  grep " [D] " ../../stub/$SHORTNAME.nm >> ../nmshared
  ;;
esac

# resolve all the references
foo=1
for i in $LIBSRC ; 
do
  echo Resolving $i .....

  $nm ../../$i | grep -v " [tcbdU] " > nmstatic; 

  $libresolve  -a ../nmshared -s nmstatic;

  $cc -c *.s;
  $ar -r ../"$i" *.o;
  $ranlib ../"$i";

  # this is for building other shared lib which depends on this one.
  # cp ../"$i" $AUXLIBDIR

  # we need __shared.o to get the lib name
  if [ $foo = 1 -a x"$SHLIB_SYMBOL"x != xx ]
  then
    mv ../__shared.o .
    $libresolve -u $SHLIB_SYMBOL -a ../nmshared -s nmstatic;

    $cc -c *.s;
    $ar -r ../"$i" *.o;
    $ranlib ../"$i";
    foo=2
  fi
  /bin/rm -f *.o;
  /bin/rm -f *.s;
done  

# safty
/bin/rm -f *.o;

cd ..
/bin/rm -rf sharedlib

cp nmshared $SHORTNAME.nm

/bin/rm -rf nmshared
mv $SHAREDLIB bar
$strip bar
mv bar $SHAREDLIB
