#!/bin/sh

# append_db
# Written by Thomas Esser <te@informatik.uni-hannover.de>, Nov., 1994

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
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

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

# 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

if [ $? != 0 ]; then
	cat >> $db_file <<-eof
		$dir:
		$file
	eof
fi >&2
