#!/bin/sh
#
# texlive-update-cnf - MacPorts utility to regenerate a TeX Live config
# file by concatenating the per-port snippets that other texlive-*
# ports have dropped into the corresponding *.d directory under
# /opt/local/etc/texmf.
#
# Usage: texlive-update-cnf <target>

set -eu

TARGET=${1:-}

case "$TARGET" in
    fmtutil.cnf)
        SRC="/opt/local/etc/texmf/fmtutil.d"
        SRCEXT="cnf"
        DST="/opt/local/var/db/texmf/web2c/fmtutil.cnf"
        COMMENT="#"
        ;;
    language.dat)
        SRC="/opt/local/etc/texmf/language.d"
        SRCEXT="dat"
        DST="/opt/local/var/db/texmf/tex/generic/config/language.dat"
        COMMENT="%"
        ;;
    language.def)
        SRC="/opt/local/etc/texmf/language.d"
        SRCEXT="def"
        DST="/opt/local/var/db/texmf/tex/generic/config/language.def"
        COMMENT="%"
        ;;
    language.dat.lua)
        SRC="/opt/local/etc/texmf/language.d"
        SRCEXT="lua"
        DST="/opt/local/var/db/texmf/tex/generic/config/language.dat.lua"
        COMMENT="--"
        ;;
    updmap.cfg)
        SRC="/opt/local/etc/texmf/updmap.d"
        SRCEXT="cfg"
        DST="/opt/local/var/db/texmf/web2c/updmap.cfg"
        COMMENT="#"
        ;;
    texmf.cnf)
        SRC="/opt/local/etc/texmf/texmf.cnf.d"
        SRCEXT="cnf"
        DST="/opt/local/etc/texmf/texmf.cnf"
        COMMENT="%"
        ;;
    *)
        echo "Usage: $0 (fmtutil.cnf | language.dat | language.def | language.dat.lua | updmap.cfg | texmf.cnf)" >&2
        exit 1
        ;;
esac

TMPFILE="$DST.tmp"
trap 'rm -f "$TMPFILE"' EXIT INT TERM

# language.def needs a version header as the first line, before everything else.
if [ "$TARGET" = "language.def" ] ; then
    echo "%% e-TeX V2.0;2" > "$TMPFILE"
else
    : > "$TMPFILE"
fi

# Write header
cat >> "$TMPFILE" <<EOF
$COMMENT$COMMENT
$COMMENT$COMMENT This file should not be edited directly!
$COMMENT$COMMENT
$COMMENT$COMMENT It was automatically generated by $0
$COMMENT$COMMENT from the contents of $SRC
$COMMENT$COMMENT on $(date).
$COMMENT$COMMENT
EOF

# Process snippets in sorted (glob) order, which matches the previous `ls` order.
# If the directory is empty, the glob expands to the literal pattern; the -f
# test skips it so we still produce a valid (header-only) output file.
for file in "$SRC"/*."$SRCEXT" ; do
    [ -f "$file" ] || continue
    cat >> "$TMPFILE" <<EOF


$COMMENT$COMMENT
$COMMENT$COMMENT Contents of $file
$COMMENT$COMMENT

EOF
    cat "$file" >> "$TMPFILE"
done

# language.def needs a default language at the very end.
if [ "$TARGET" = "language.def" ] ; then
    cat >> "$TMPFILE" <<EOF

%
% The following line must be the last in the file.
%
\\uselanguage{USenglish}
EOF
fi

# language.dat.lua needs a closing brace at the very end.
if [ "$TARGET" = "language.dat.lua" ] ; then
    echo "}" >> "$TMPFILE"
fi

# Atomically install
mv "$TMPFILE" "$DST"
trap - EXIT INT TERM
