#!/bin/sh
#
# TLpurge.sh
# (c) 2008 Ulrich M. Schwarz, ulmi at absatzen dot de
#
# This file is provided under the terms of the 
# LaTeX Project Public License, version 1.3a, the full text
# of which can be obtained from http://www.latex-project.org/
#
# This work has the maintenance-status: author-maintained.
#
#$Id: TLpurge.sh,v 1.2 2008/09/28 12:40:01 ulmi Exp ulmi $

LOCALDIR=$(kpsexpand \$TEXMFLOCAL)
USERDIR=$(kpsexpand \$TEXMFHOME)
VERBOSE=false
PARANOID=false

for param in $@; do
  case $param in 
    --help)
      cat <<EOF
Tlpurge.sh [Options ...]
Scan TeXMF trees for duplicate sty and cls files by checking whether files in
user and local TeXMF tree are present in other trees as well.

Options:
--skiphome:  do not check TEXMFHOME for duplicates
--skiplocal: do not check LOCALTEXMF for duplicates
--paranoid:  report all duplicate files. By default, files that are newer
             timestampwise in the local/user tree are not reported.

--help: this message

EOF
      exit 0
    ;;
    --skiphome)
      USERDIR=""
    ;;
    --skiplocal)
      LOCALDIR=""
    ;;
    --paranoid)
      PARANOID=true
    ;;
    --verbose)
      VERBOSE=true
  esac
done

for dir in "$LOCALDIR" "$USERDIR"; do
  test -z $dir && continue
  echo "Checking tree $dir..."

  for lfi in $(find $dir -name \*.cls -o -name \*.sty -print ); do
    $VERBOSE && echo "Checking $(basename $lfi)... "
    ALLLOCATIONS=$( kpsewhich -a $(basename $lfi) );
    for ofi in $ALLLOCATIONS; do
      if test $lfi -ef $ofi ; then 
        # Of course, all locations includes the one in $dir
        continue
      fi
      if $PARANOID ; then
        # In case of paranoia, just report immediately.
        echo "File $(basename $lfi), found in $(dirname $lfi), present in "
        echo -e "$ALLLOCATIONS"
        break # ofi
      fi
      if cmp -s $lfi $ofi; then
          echo "File $(basename $lfi) in $(dirname $lfi) and identical file in "
          echo -e "\t$ofi"
      elif test $lfi -nt $ofi ; then
          $VERBOSE || continue
          echo "File $(basename $lfi) in $(dirname $lfi) and older file in "
          echo -e "\t$ofi"
      else
          echo "File $(basename $lfi) in $(dirname $lfi) and newer file in "
          echo -e "\t$ofi"
          #ls -lh $fi $ofi
      fi
    done # ofi
  done #   fi
done #     dir

