#! /bin/sh
# $Id: elilink,v 1.1 1990/04/04 15:24:12 tony Exp $
# Copyright, 1989, The Regents of the University of Colorado

ELILINK=elilink

#
# Test for correct parameters
#
if test $# -ne 2
then
	echo "usage: elilink working-directory master-directory"
	exit 1
fi
bombed="FALSE"
if test ! -d $1
then
	echo "      WARNING --- $1 is not an existing directory"
	bombed="TRUE"
fi
if test ! -d $2
then
	echo "   WARNING --- $2 is not an existing directory"
	bombed="TRUE"
fi
if test ${bombed} = "TRUE"
then
	echo Elilink decent terminated at `pwd`, unable to process directory $1
	exit 1
fi

#
# Set up work directory and master directory (link directory) names
#
templ=`pwd`
if test `echo $1 | cut -c1` = "/"
then
	workdir=$1
else
	workdir=${templ}/$1
fi
if test `echo $2 | cut -c1` = "/"
then
	linkdir=$2
else
	linkdir=${templ}/$2
fi

#
# Test to insure that the working directory and the link directory are different.
#
if test ${workdir} = ${linkdir}
then
	echo "   WARNING --- working directory is the same as the link directory"
	echo "               ${workdir}"
	echo Elilink decent terminated at `pwd`
	exit 1
fi

#
# Change to the work directory
#
cd ${workdir}

#
# For each directory in the work directory, call elilink recursively
#
for f in *
do
	if test -d ${f} -a ! -h ${f}
	then
        newlinkdir=${linkdir}/${f}
        ${ELILINK} ${f} ${newlinkdir}
	fi
done

#
# Now go through every directory entry in the work directory
#
echo Now working on ${workdir}
binaries="FALSE"
for f in *
do
#
# If it is another directory and not a link, set "binaries" to TRUE
#
	if test -d ${f} -a ! -h ${f}
	then
		binaries="TRUE"
	fi
#
# If it is a file and not a binary replace it with a hard link
#     otherwise set "binaries" to TRUE
#
	if test -f ${f}
	then
                if cmp -s ${f} ${linkdir}/${f}
		then
			echo "      . . . establishing link for ${f}"
			rm -f ${f}
			ln ${linkdir}/${f} ${f}
		else
			echo "      . . . the ${f} files are not identical"
			binaries="TRUE"
		fi
	fi
done

#
# If there are no binaries in this directory or below it
#     erase this directory and replace it with a soft link
#
if test ${binaries} = "FALSE"
then
	echo "   . . . no binaries in ${workdir}, linking directory"
	rm -f *
	cd ..
	rmdir ${workdir}
	ln -s ${linkdir} ${workdir}
else
	cd ..
fi
echo Done with ${workdir}
