#! /bin/bash
################################################################################
#
#  build links to Perl code separate from kPerl
#
################################################################################


# environment variables
if [ ! -d ${TEMPPATH:=/tmp} ] || [ ! -w $TEMPPATH ] ; then
  echo "ERROR: need tmp path write permission" >&2
  exit 1
fi

# path constants and variables
ftmpl=$TEMPPATH/`basename $0 .sh`.ls
ftmpf=$TEMPPATH/`basename $0 .sh`.find
pfind='../..'
#pfindadd=/usr/devel/library/lit-org                         #LLL#
if [ -d "$pfindadd" ] ; then
  pfind="$pfind $pfindadd"
fi


# command line interface
if [ -L "$0" ] ; then
  echo "you need to call the script to its physical path" >&2
  exit 1
fi


### work

# perform actions in directory where the script (physically) resides
cd `dirname $0`

# check the entries of the perl search path
for p in $pfind ; do
if [ ! -d "$p" ] || [ ! -r "$p" ] ; then
  echo "unable to read directory path" `dirname $0`/$pfind >&2
  exit 1
fi
done

# locate perl files in the search paths
find $pfind -type f -name '*.p[lm]'  \
  | egrep -v '(kPerl/|perl-xtra)'  \
  | egrep -v 'PostScript_pm'  \
  > $ftmpf
if [ ! -s "$ftmpf" ] ; then
  echo "ERROR: unable to find Perl files in file trees:" $pfind >&2
  echo "pwd is" `dirname $0` >&2
  rm -f $ftmpf  2>/dev/null
  exit 1
fi
fll=`cat $ftmpf`

# remind and delete old links
find . -type l | sort > $ftmpl
lnumo=`cat $ftmpl | wc -l`
rm `cat $ftmpl`  2>/dev/null

# create links
for fl in $fll ; do
  ln -s $fl
done
lnumn=`find . -type l | wc -l`
if [ "$lnumn" -lt "$lnumo" ] ; then
  echo `basename $0` "WARNING: less entries than previously, $lnumo -> $lnumn" >&2
  find . -type l | sort | diff $ftmpl - >&2
  echo -- '------' >&2
  echo "kept temporary files:" $TEMPPATH/`basename $0 .sh`'.*' >&2
  exit 1
fi

# tidy up, exit
rm -f $ftmpf $ftmpl  2>/dev/null
exit 0
