#!/bin/sh

# append_db: add new files to the filename database. Kpathsea ignores
# all files that are not below $TEXMF, so we do nothing if the file
# is not somewhere below that tree.

# Written by Thomas Esser <te@informatik.uni-hannover.de>, Nov., 1994
# Last change: Thu Aug  8 00:45:16 MET DST 1996.

# TODO:
#   There are possible race conditions when ed writes ls-R back to disk.
#   Locking would be nice. Any ideas how one could do this here?

progname=`basename $0`

: ${TEXMF=`kpsetool -v '$TEXMF'`}
if [ -z "$TEXMF" ]; then
  if [ ! -f "`kpsetool -w cnf texmf.cnf`" ]; then
    echo "$progname: global Kpathsea configurarion file texmf.cnf not found." >&2
    echo >&2
    echo "Please set the environment variable TETEXDIR or TEXMFCNF correctly." >&2
    echo "For details see the teTeX and the Kpathsea manual" >&2
    exit
  fi
fi

db_file=$TEXMF/ls-R
control_string='% This is file ls-R. Maintained by texhash and append_db.'

case $# in
2)  ;;
*)  echo "Usage: append_db dir file" >&2
  exit
  ;;
esac

dir=$1
origdir=$1
file=$2

if test ! -d "$dir"; then
  echo "$progname: error: not a directory '$dir'." >&2; exit
fi

if test ! -f "$dir/$file"; then 
  echo "$progname: error: not a file '$dir/$file'." >&2; exit
fi

case "$dir" in
  ${TEXMF}*) ;;
  *) exit 1;;
esac

dir=`echo $dir | sed 's@^'"$TEXMF"'/@./@;s@^'"$TEXMF"'$@./@'`

test -f $db_file || texhash
test -f $db_file || { echo "$progname: file $db_file does not exist." >&2; exit 1; }

if test ! -w "$db_file" ; then
  echo "$progname: error: cannot write to file $db_file." >&2
  exit
fi

if [ "`sed q $db_file`" != "$control_string" ]; then
  echo "$progname: not a db-file: $db_file. Aborted." >&2
  exit 1
fi

# entry already there?
test -n "`TEXINPUTS=\!\!$origdir kpsetool -w tex $file 2>/dev/null`" && exit 0

# we need to escape / in the dirname for ed, as wee search for it with /../.
ed $db_file > /dev/null 2>&1 <<-eof
	/^`echo $dir | sed 's@/@\\\\/@g;s/\\./\\\\./g'`:\$/a
	$file
	.
	w
	q
eof

# did ed succeed?
test -n "`TEXINPUTS=\!\!$origdir kpsetool -w tex $file 2>/dev/null`" && exit 0

# no? so, append the directory and the filename:
cat >> $db_file <<-eof
	$dir:
	$file
eof
