#!/bin/sh

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

# texhash is intended to rebuild ls-R. Some special care is
# taken to keep ownership (if called by root) and file modes
# of ls-R. It should be called from the tex-admin after installing
# new files in $TEXMF.

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

trap 'cd / ; rm -f $db_file_tmp; exit' 1 2 15

if test ! -d "$TEXMF" ; then
    echo "$progname: fatal error: directory '$TEXMF' not found."
    echo "Please check your setup."
    exit
fi >&2

db_file=`\ls -l $TEXMF/ls-R 2> /dev/null | awk '{print $NF}'`
test -z "$db_file" && db_file=$TEXMF/ls-R
db_dir=`echo $db_file | sed 's/^[^\/]*$/./; s/\/[^\/]*$//'`
db_file_tmp=$db_dir/ls-R-tmp$$

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

echo "$progname: updating $db_file ... " >&2
if test ! -f $db_file; then
    touch $db_file
    chmod 666 $db_file
fi

# copy the file to preserve as much of the permissions as possible.
rm -f $db_file_tmp
cp -p $db_file $db_file_tmp

# make sure, we can write the file:
chmod +w $db_file_tmp

# some poeple set noclobber somewhere else, so make sure to unset it.
unset noclobber
# append_db depends on the next line. DO NOT CHANGE THE STRING.
echo '% This is file ls-R. Maintained by texhash and append_db.' > $db_file_tmp

# the main task:
(cd $TEXMF; \ls -LRa ./ /dev/null | grep -v '^\.*$' | sed 's@\.//@./@; /^\.\.?$/d' ) 2>/dev/null >> $db_file_tmp

echo "$progname: Done." >&2
rm -f $db_file
mv $db_file_tmp $db_file
