#!/bin/sh
# MakeTeXls-R -- create or rebuild ls-R.
# Suitable for calling from cron, as in:
# 0 * * * * cd /your/texmf/root && /usr/local/bin/MakeTeXls-R
# 
# Keeps ls-R world-writable, so anyone can update it (via MakeTeXPK etc.).
# 
# Originally written as `texhash' by Thomas Esser
# <te@informatik.uni-hannover.de>, Okt., 1994.
# Public domain.

version='$Id: MakeTeXls-R,v 1.6 1997/02/08 15:52:15 karl Exp karl $'
usage="Usage: $0.
  Rebuild the ls-R filename database completely."
mt_min_args=0
mt_max_args=0

: ${TEXMFMAIN=`kpsewhich -expand-var='$TEXMFMAIN'`}
if test -z "$TEXMFMAIN"; then
  echo "$0: No \$TEXMFMAIN; set the environment variable or in texmf.cnf." >&2
  exit 1
fi
: ${TEXMFLS_R=`kpsewhich -expand-var='$TEXMFLS_R'`}
test -n "$TEXMFLS_R" || TEXMFLS_R=$TEXMFMAIN
: ${TEXMFCNF_DIR=`kpsewhich -expand-var='$TEXMFCNF_DIR'`}
test -n "$TEXMFCNF_DIR" || TEXMFCNF_DIR=$TEXMFMAIN/web2c
. $TEXMFCNF_DIR/MakeTeXcommon

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

# Use ls -l to follow a possible symlink to get the right filesystem, 
db_file=`\ls -l $TEXMFLS_R/ls-R 2>/dev/null | awk '{print $NF}'`
test -z "$db_file" && db_file=$TEXMFLS_R/ls-R
db_dir=`echo $db_file | sed 's%/[^/][^/]*$%%'` # can't rely on dirname
db_file_tmp=$db_dir/lsR$$.tmp # PID in the first 8 chars (MS-DOS)

test -w "$db_dir" || { echo "$0: Cannot write to $db_dir." >&2; exit 1; }

if test ! -f $db_file; then
    cp /dev/null $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 2>/dev/null

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

tty -s && echo "$0: Updating $db_file... "
# Some people set noclobber somewhere else, so make sure to unset it.
unset noclobber
echo "$ls_R_magic" >$db_file_tmp

# The main task. We ls two things so the top-level directory name ends
# up in the output, so top-level files can be found via ls-R. Probably
# irrelevant in practice.
# The sed command is because on new FreeBSD/NetBSD systems, ls -LAR ./
# produces .//. Sigh.
(cd $TEXMFLS_R && ls -LAR /dev/null ./ 2>/dev/null) \
| sed 's@\.//@./@' \
>>$db_file_tmp

tty -s && echo "$0: Done."
rm -f $db_file
mv $db_file_tmp $db_file
