#! /bin/sh -
if [ $# -eq 0 ]
then
	echo "Usage: Splus $0 [-o libname] sourcefile1 [sourcefile2 ...]" 1>&2
	exit 0
fi

SHOME=`Splus SHOME`
LDARGS=""
FIRSTFILE=""
SRCS=""
OBJS=""

SHOBJ_SUFFIX=".so"
case `Splus PLATFORM` in
HP*) SHOBJ_SUFFIX=.sl ;;
esac

while [ "X$1" !=  "X" ]
do
	case $1 in
	-o)
		shift
		if [ "X$LIBNAME" != "X" ]
		then
			echo "Error: 2 -o flags" 1>&2
			echo "Usage: Splus $0 [-o libname] sourcefile1 [sourcefile2 ...]" 1>&2
			exit 1
		fi
		LIBNAME=$1
		if [ "X$LIBNAME" = "X" ]
		then
			echo "Error: -o not followed by filename" 1>&2
			echo "Usage: Splus $0 [-o libname] sourcefile1 [sourcefile2 ...]" 1>&2
			exit 1
		fi
		shift
		;;
	*.?)
		if [ "X$FIRSTFILE" = "X" ]
		then
			FIRSTFILE=$1
		fi
		OBJS="$OBJS `echo $1 | sed -e 's/\..$/.o/'"
		SRCS="$SRCS $1"
		shift
		;;
	*)
		LDARGS="$LDARGS $1"
		shift
		;;
	esac
done
if [ "X$FIRSTFILE" = "X" ]
then
	echo "Error: No files given" 1>&2
	echo "Usage: Splus $0 [-o libname] sourcefile1 [sourcefile2 ...]" 1>&2
	exit 1
fi
if [ "X$LIBNAME" = "X" ]
then
	LIBNAME=`basename $FIRSTFILE`
	LIBNAME=`echo $LIBNAME | sed -e "s/\..\$/$SHOBJ_SUFFIX/"`
#	echo "No -o, so setting LIBNAME to $LIBNAME" 1>&2
fi
LDARGS="-o $LIBNAME $LDARGS"

# Look for special makefiles for compiling code for shared objects
somf=""
for file in $SHOME/newfun/lib/S_soMakefile soMakefile
do
	if [ -r $file ]
	then
		somf="$somf -f $file"
	fi
done

# Make temporary directory to do compiling and linking in
# We do this so that *.o files compiled with PIC flags are
# not left around to confuse dyn.load or 'ld -r'.
tmpdir=dir_so.$$
mkdir $tmpdir || exit 1

#
# Modifcations to handle the case when the object is a 
# relative link.  Linking to a relative link doesn't work,
# so a copy is done instead.
#

if [ "X$SRCS" != "X" ]
then
   for i in `echo "$SRCS"`
   do
      islink=`ls -l $i | awk '{print $1}' | cut -c1-1`
      if [ "$islink" = "l" ]
      then
         cp $i $tmpdir
      else
         ln $i $tmpdir
      fi
   done
fi

#
#  Handle processing of *.h files.
#
set -- *.h
if [ "X$1" != "X*.h" ]
then
   while [ $# != 0 ]
   do
      islink=`ls -l $1 | awk '{print $1}' | cut -c1-1`
      if [ "$islink" = "l" ]
      then
         echo "//  Note :  Copying file $1 to $tmpdir."
         cp $1 $tmpdir
      else
         echo "//  Note :  Linking file $1 to $tmpdir."
         ln $1 $tmpdir 2>/dev/null
      fi
      shift
   done
fi
cp soMakefile $tmpdir 2>/dev/null
cd $tmpdir

Splus COMPILE $somf $LIBNAME SHLIB=$LIBNAME OBJS="$OBJS" 1>&2 ||
	{ cd .. ; rm -rf $tmpdir ; exit 1 ; }
# echo "Got past the compilation and linking" 1>&2
rm ../$LIBNAME 2>/dev/null
ln $LIBNAME ../$LIBNAME
cd ..
rm -rf $tmpdir
echo $LIBNAME
