#!/bin/bash -e
#
# update-updmap --- Generate updmap.cfg for all the trees
# Copyright (C) 2012 Norbert Preining
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; version 2 dated June, 1991.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program; see the file COPYING. If not, write to the
# Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
# Boston, MA  02110-1301 USA.

version="1.0"
progname=$(basename "$0")

SNIPPET_BASE=/var/lib/tex-common/fontmap-cfg
SNIPPET_OLD_BASE=/etc/texmf/updmap.d

# this needs to be kept in sync with dh_installtex
COMPONENTS="texmf texlive"


usage="Usage: $progname [OPTION...]
Generate updmap configuration files.

Options:
      --checks           perform sanity checks on the generated config file
      --quiet            don't write anything to the standard output during
                         normal operation
      --help             display this help message and exit
      --version          output version information and exit"


# This ensures that if $tempfile is in the *environment*, we won't erase
# the file it could point to in case the script is killed by a signal before
# it has had a chance to even create its temporary file.
tempfile=""


cleanup()
{
    rc=$?
    [ -n "$tempfile" ] && rm -f "$tempfile"
    exit $rc
}

perform_contents_check ()
{
    fn="$1"
    grep -i '^\W*\(Mixed\|Kanji\)\?Map' "$fn" | while read foo map ; do
        # now check the existence of the hyphenation file
        if [ -z $(kpsewhich -format=map $map) ] ; then
           cat >&2 <<EOF
The config file $fn references a file not in the kpathsea database:
    $map
Calling updmap(-sys) will break!
This may be ok, but it could also be a typing error.
EOF
        fi
    done
}


####################################################
#
# STUFF THAT IS ONLY HERE TO KEEP COMPATIBILITY WITH
# PACKAGES OUTSIDE DEBIAN THAT SHIP OLD updmap.d 
# FILES AND WE CANNOT BREAK AGAINST THEM
#
####################################################

# include_file <file path>
include_file()
{
    file="$1"
    printf "\n# ## From file: $file\n"
    cat "$file"
    echo "# End of file: $file"
}

# do_not_include_file <file path>
do_not_include_file()
{
    file="$1"

    cat <<EOF

#
# $file not included because either it wasn't
# up-to-date (conffile update pending) or the package shipping it was
# apparently removed (no corresponding .list file in
# $SNIPPET_BASE/).
#
EOF
}

handle_file()
{
    file="$1"
    DebPkgProvidedMaps_magic_comment="^[#%] -_- DebPkgProvidedMaps -_-"
    # Does the file have a dpkg-new sister?
    if [ -f "${file}.dpkg-new" ]; then
      do_not_include_file "$file"
    else
      # Does the file have the magic comment?
      if grep -E "$DebPkgProvidedMaps_magic_comment" "$file" >/dev/null; then
        # Is the package "$file" comes from still installed?
        if [ -d "$SNIPPET_BASE" ] \
            && find "$SNIPPET_BASE" -type f -name '*.list' -print0 \
            | xargs -0r cat \
            | grep -E "^$(basename "$file" .cfg)\$" >/dev/null;
        then
            include_file "$file"
        else
            do_not_include_file "$file"
        fi
      else
        include_file "$file"
      fi
    fi
}

#######################################################
#
# end of backward compatibility stuff
#
#######################################################


# The list of signals to trap is taken from teTeX 3's updmap script, but they
# have been converted to signal names because we can only rely on these on
# POSIX systems.
trap 'cleanup' HUP INT QUIT BUS PIPE TERM


# -v (verbose) is here for backward compatibility only.
TEMP=$(getopt -o +vc:o: --longoptions \
    check,quiet,help,version \
    -n "$progname" -- "$@")

case $? in
    0) : ;;
    1) echo "$usage" >&2; exit 1 ;;
    *) exit 1 ;;
esac

# Don't remove the quotes around $TEMP!
eval set -- "$TEMP"

# ****************************************************************************
# *                                 Defaults                                 *
# ****************************************************************************
quiet=0
dochecks=0

# ****************************************************************************
# *                             Options handling                             *
# ****************************************************************************
while true; do
    case "$1" in
        --quiet) quiet=1; shift ;;
        --check) dochecks=1; shift ;;
        -v) printf "\
${progname}'s -v option is deprecated. The default mode of operation will
be verbose as soon as enough packages use the --quiet option. Please update
your scripts accordingly.\n\n" >&2; quiet=0; shift ;;
        --help) echo "$usage"; exit 0 ;;
        --version) echo "$progname $version"; exit 0 ;;
        --) shift; break ;;
	*) echo "$progname: unexpected option '$1'; please report a bug." >&2
            exit 1 ;;
    esac
done

# Non-option arguments are not allowed.
if [ $# -ne 0 ]; then
    echo "$usage" >&2
    exit 1
fi

# ****************************************************************************
# *                               Actual work                                *
# ****************************************************************************

updated_files=""
for tree in $COMPONENTS ; do
    if [ $tree = "texmf" ] ; then
        # output_file=/usr/share/texmf/web2c/updmap.cfg
        output_file=/var/lib/texmf/updmap.cfg-DEBIAN
    elif [ $tree = "texlive" ] ; then
        # output_file=/usr/share/texlive/texmf-dist/web2c/updmap.cfg
        output_file=/var/lib/texmf/updmap.cfg-TEXLIVEDIST
    else
        echo "$progname: that cannot happen!" >&2
        exit 1
    fi

    # create output dir in any case ...
    mkdir -p $(dirname $output_file)

    #
    if [ $quiet = 0 ]; then
        if [ -f "$output_file" ]; then
	        printf "Regenerating '${output_file}'... "
        else
            printf "Generating '${output_file}'... "
        fi
    fi

    # Creating the temporary file in the output directory gives it 
    # automatically the default permissions appropriate for that 
    # directory, according to the user's umask. When it is complete, 
    # we'll be able to rename it atomically to the desired output 
    # file, which will therefore have the right permissions.
    tempfile="updmap.$tree.new"

    if ! printf "" > "$tempfile" ; then
        echo "$progname: cannot write to the temporary file '$tempfile'" >&2
        exit 1
    fi

    printf "\
### This file was automatically generated by ${progname}.
#
# Any local change will be overwritten. Please see the documentation
# of updmap on how to override things from here.
#
###\n" >> "$tempfile"

    # From now on, $tempfile must be deleted on exit; therefore, cleanup() should
    # be used.

    if [ -d "$SNIPPET_BASE/$tree" ] ; then
        find "$SNIPPET_BASE/$tree"  -maxdepth 1 -type f -name '*.cfg' \
            -exec cat '{}' \; >> "$tempfile"
    fi

    if [ $tree = "texmf" ] ; then
        #
        # also include snippets in /etc/texmf/updmap.d but give
        # big fat warnings that this might create problems!!!
        if [ -d $SNIPPET_OLD_BASE ] ; then
            old_files=$(find $SNIPPET_OLD_BASE -maxdepth 1 -type f -name '*.cfg' | LC_COLLATE=C sort)
            if [ -n "$old_files" ] ; then
                cat >&2 <<EOF


Warning: Old configuration style found in $SNIPPET_OLD_BASE
Warning: For now these files have been included, 
Warning: but expect inconsistencies.
Warning: These packages should be rebuild with tex-common.
Warning: Please see /usr/share/doc/tex-common/NEWS.Debian.gz
EOF
                for file in $old_files ; do
                    echo "Warning: found file: $file" >&2
                done
                echo "" >&2
            fi

            for file in $old_files  ; do
                handle_file $file >> "$tempfile"
            done
        fi
    fi

    # This is atomic.
    mv "$tempfile" "$output_file"
    updated_files="$updated_files\t$output_file\n";

    # Check wether the generated file is decent, if all necessary files are
    # installed, etc.
    if [ "$dochecks" = 1 ] ; then
        perform_contents_check "$output_file"
    fi
    if [ $quiet = 0 ]; then
        printf "done.\n"
    fi

done

if [ $quiet = 0 ] && [ -n "$updated_files" ] ; then
    echo "$progname has updated the following file(s):"
    printf "$updated_files"
    echo "If you want to enable the map files with this new file,"
    echo "you should run updmap-sys or updmap."
fi


# vim:set expandtab tabstop=4 autoindent: #
