#!/bin/sh

[ -x ./gathertree.local ]  && exec ./gathertree.local $@

if [ "x$SYSTEMLN" = "x" ]; then SYSTEMLN="./system_ln"; fi

SRC=$1
DST=$2

[ ! -d $SRC ] && exit 0;

# remove all temporary files
rm -f temp.d temp.f temp.m temp.l tmp*.awk
# find all directories including and below SRC
(cd $SRC ; find . -name CVS -prune -o -type d -print )|sed -e s@.@@> temp.d
# find all files below SRC
(cd $SRC ; find . -name CVS -prune -o -type f -print )|sed -e s@.@@> temp.f
# generate shell script to make directories if they do not exist
awk '{print "if [ ! -d '$DST'"$1" ] ; then mkdir '$DST'"$1" ; fi";}' <temp.d >temp.m

# generate shell script to symlink files
case "$SRC" in
  /*)
    echo '{ print "'$SYSTEMLN' '$SRC'"$1" '$DST'"$1 }' > tmp2.awk
    ;;
  *)
    # Count the number of directories up we have to go; print out list
    echo '{ nUp=0; for (i=1;i<NF;i++)
		if ($i=="..") nUp--;
		else if ($i!=".")nUp++;
	pah=""; for (i=0;i<nUp;i++) {pah=pah"../"}; print pah
    } ' > tmp1.awk
    echo '{print "pah=`echo '$DST'"$1" | awk -F/ -f tmp1.awk`" ;' > tmp2.awk
    echo ' print "'$SYSTEMLN' $pah'$SRC'"$1" '$DST'"$1 }' >> tmp2.awk
    ;;
esac

awk -f tmp2.awk <temp.f >temp.l
# execute shell script to create directories
sh temp.m
# execute shell script to link files 
sh temp.l
[ -f $SRC/gather.tree ] && sh $SRC/gather.tree
# remove temporary files
rm -f temp.d temp.f temp.m temp.l tmp*.awk
