#!/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=1

# The main system texmf tree:
: ${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

. $TEXMFMAIN/web2c/MakeTeXcommon

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

test $# = 0 && {
  OIFS=$IFS; IFS=:; set x `kpsewhich  -show-path=ls-R`; shift; IFS=$OIFS;
}
for TEXMFLS_R in "$@"; do
  # 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/ls-R-tmp$$

  test -d "$db_dir" || $TEXMFMAIN/web2c/MakeTeXmkdir "$db_dir"
  test -w "$db_dir" || { echo "$0: Cannot write to $db_dir. Skipping..." >&2; continue; }

  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 -LRa /dev/null ./ 2>/dev/null) |
    sed 's@\.//@./@; /^\.\.?$/d' >>$db_file_tmp

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