#!/bin/sh
# update-texmf
# License: GPL

set -e

TXMF=/etc/texmf
TXMF_CNF=$TXMF/web2c/texmf.cnf
CNFDIR=${TXMF}/texmf.d
TMPDIR=`mktemp -d`
TMPTXMF=`mktemp -p ${TMPDIR} texmfXXXXXXX`

VERBOSE=false
DEBUG=false
while [ $# -ne 0 ]; do
  case $1 in
    -v|--verbose)
      VERBOSE=true
      shift;;
    -d|--debug)
      DEBUG=true
      VERBOSE=true
      shift;;
    *)
      echo "unknown option: $1"
      exit 1
      ;;
  esac
done

# test wether /etc isn't mounted read-only
if touch /etc/texmf/is_rw 2>/dev/null; then
  rm -f /etc/texmf/is_rw
else
  echo "Directory /etc/texmf/ not writeable. Exiting."
  exit 1
fi

CNFFILES=`find ${CNFDIR} -name \*.cnf -print | sort`
if [ $DEBUG = true ]; then
  echo "Using the following files:"
  for file in $CNFFILES; do
    echo $file
  done
fi

if [ -z "$CNFFILES" ] ; then
  # no config files are found, remove texmf.cnf if it is there
  rm -rf /etc/texmf/web2c/texmf.cnf
  exit 0
fi

if [ "${VERBOSE}" = "true" ]; then
  if [ -f "${TXMF_CNF}" ]; then
    echo -n "Merging information from /etc/texmf/texmf.d/ into ${TXMF_CNF} ... " >&2
  else
    echo -n "Generating ${TXMF_CNF} ... " >&2
  fi
fi

cat > ${TMPTXMF} <<EOF
%%% This file is automatically generated by update-texmf
%
% PLEASE DO NOT EDIT THIS FILE DIRECTLY. It is meant to be generated from 
% files in /etc/texmf/texmf.d/. 
%
% Therefore, if you want a smooth upgrade, please edit the files
% in ${CNFDIR}, 
% or create an additional one (with the extension '.cnf'),
% and invoke update-texmf.
%
%%%

EOF

for i in ${CNFFILES}; do
    if [ $i = "/etc/texmf/texmf.d/05TeXMF.cnf" ] ||
       [ $i = "/etc/texmf/texmf.d/15Plain.cnf" ] ||
       [ $i = "/etc/texmf/texmf.d/45TeXinputs.cnf" ] ||
       [ $i = "/etc/texmf/texmf.d/55Fonts.cnf" ] ||
       [ $i = "/etc/texmf/texmf.d/65BibTeX.cnf" ] ||
       [ $i = "/etc/texmf/texmf.d/75DviPS.cnf" ] ||
       [ $i = "/etc/texmf/texmf.d/80DVIPDFMx.cnf" ] ||
       [ $i = "/etc/texmf/texmf.d/85Misc.cnf" ] ||
       [ $i = "/etc/texmf/texmf.d/90TeXDoc.cnf" ] ||
       [ $i = "/etc/texmf/texmf.d/95NonPath.cnf" ] ; then
       echo "Ignoring $i during generation of texmf.cnf, please remove manually!" >&2
       echo "%%% IGNORED: $i" >> ${TMPTXMF}
       continue
    fi
    echo "%%% From file: $i" >> ${TMPTXMF}
    cat $i >> ${TMPTXMF}
    echo "%%% End of file: $i" >> ${TMPTXMF}
done

mkdir -p ${TXMF}/web2c
cp ${TMPTXMF} ${TXMF_CNF}
rm -r ${TMPDIR}
chmod 644 ${TXMF_CNF}

if [ "${VERBOSE}" = "true" ]; then
  echo "done"
fi

#
# Let vim know that we don't want tabs
# vim:set expandtab: #
