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

set -e

TXMF=/etc/texmf
TXMF_CNF=$TXMF/texmf.cnf
CNFDIR=${TXMF}/texmf.d
VARD=/var/lib/texmf/web2c
MD5SUMS=/usr/share/tex-common/texmf.cnf.md5sum.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

if [ -f ${CNFDIR}/05TeXMF.cnf ] ; then
  CNFFILES=`/bin/ls -1 ${CNFDIR}/*.cnf`
  if [ $DEBUG = true ]; then
    echo "Using the following files:"
    for file in $CNFFILES; do
      echo $file
    done
  fi
else
  echo "update-texmf: Basic configuration file ${CNFDIR}/05TeXMF.cnf missing." >&2
  echo "Exiting." >&2
exit 1
fi

if [ "${VERBOSE}" = "true" ]; then
  if [ -f "${TXMF}/texmf.cnf" ]; then
    echo -n "Merging information from /etc/texmf/texmf.d/ into ${TXMF}/texmf.cnf ... " >&2
  else
    echo -n "Generating ${TXMF}/texmf.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/. 
%
% While changes made by users will not be overwritten, they will cause
% you trouble. You will be shown the differences between the edited and
% the newly created file. We will try to merge our and your changes, but
% that might not always work, and you will probably have to edit again.
%
% 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
    echo "%%% From file: $i" >> ${TMPTXMF}
    cat $i >> ${TMPTXMF}
    echo "%%% End of file: $i" >> ${TMPTXMF}
done

# now copy the file with historical md5sums into TMPDIR, 
# invoke ucf, and then remove the suggested texmf.cnf.
cp -a ${MD5SUMS} ${TMPTXMF}.md5sum.d
ucf --debconf-ok --three-way ${TMPTXMF} ${TXMF}/texmf.cnf
if [ $DEBUG = true ]; then
  echo
  echo -n "Keeping temporary file ${TMPTXMF} ... "
else
  rm -r ${TMPDIR}
fi
chmod 644 ${TXMF}/texmf.cnf

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

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