#!/bin/sh
#
# Starlab make helper.
#
# Place object files corresponding to non-null source files in the
# specified library ($2) in directory $1, then remove all zero-length
# C++ source files and their associated object files.
#
# Finally, touch/ranlib all dependent libraries to ensure rebuilding.
#
# Input is a list of object files.
#
if [ $# -lt 2 ]; then
    echo "Usage: $0 dirname libname  file.o ..." >&2
    exit 1
fi

dir="$1"
libname="$2"
shift; shift

if [ -z "$libname" ]; then
#
#   If the library is null, we still have to check for and remove
#   zero-length files...
#
    for f in "$@"; do
	fC=`expr match "$f" '\(.*\)\.[a-zA-Z]*$' \| match "$f" '\(.*\)' `.C
	if [ -f "$fc" -a ! -s "$fc" ]; then
	    /bin/rm -f $fc
	fi
    done
    exit
fi
#
lib=$dir/$libname
#
if [ -f "$lib" ]; then
#
#   Make a copy of the archive to check later if any change has
#   actually been made to it.
#
    /bin/mv $lib $lib.save
    /bin/cp $lib.save $lib
else
    touch $lib.save
fi
#
list=""
for f in "$@"; do
    fstem=`expr match "$f" '\(.*\)\.[a-zA-Z]*$' \| match "$f" '\(.*\)' `
    if [ -f $fstem.C -a ! -s $fstem.C ]; then	# 0-length .C file
	/bin/rm -f $fstem.C $fstem.o
    else
	list="$list $fstem.o"
    fi
done
if [ -n "$list" ]; then
    ar ruv $lib $list
fi
#
# Check for changes.  Note that ar will change the date of the library even
# if nothing is actually done.  This causes great confusion with make...
#
if [ -f $lib -a -f $lib.save ] && cmp $lib $lib.save >/dev/null 2>&1; then
#
#   No difference--move back the original, and leave .lib unchanged.
#
    /bin/mv $lib.save $lib
else
#
#   Real change--run ranlib, if necessary.
#
    $STARLAB_RANLIB $lib
    /bin/rm $lib.save
#
#   Update the local placeholder.
#
    touch .lib
#
#   Update all dependent dynamical libraries...
#
    cd $dir
    lib_list=""
#
    DYNDEP="libhdyn.a libsdyn.a libsdyn3.a"
    case "$libname" in
      libstd.a)  lib_list="libnode.a libdyn.a $DYNDEP libstar.a libhydro.a" ;;
      libnode.a) lib_list="libdyn.a $DYNDEP libstar.a libhydro.a" ;;
      libdyn.a)  lib_list="$DYNDEP" ;;
      libhdyn.a) lib_list="libsdyn.a libsdyn3.a" ;;
    esac
#
    for lib in $lib_list; do
	if [ -f $lib ]; then
	   touch $lib
	   $STARLAB_RANLIB $lib
	fi
    done
fi
