#!/bin/sh
# (setq skeleton-pair t)
# 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/tetex-bin/texmf.cnf.md5sum.d
TMPDIR=`mktemp -d`
TMPTXMF=`mktemp -p ${TMPDIR} texmfXXXXXXX`

if [ "x$1" = "x-v" ] ; then
    VERBOSE=true
else
    VERBOSE=false
fi

# 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`
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 "Regenerating ${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
#cat ${CNFFILES} >> ${VARD}/texmf.cnf_$$

# 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
rm -r ${TMPDIR}
chmod 644 ${TXMF}/texmf.cnf

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