#!/bin/sh -e
# 
# postinst maintainer script for the Debian tex-common package.
#
# Copyright (C) 2004 by Frank Küster <frank@kuesterei.ch>. 
# Copyright (C) 2012 by Norbert Preining <preining@debian.org>
#
# This file 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; either version 2 of the License, or (at your
# option) any later version.
#
# This file 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; if not, write to: The Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
#
# On Debian GNU/Linux System you can find a copy of the GNU General Public
# License in "/usr/share/common-licenses/GPL".

umask 022

#
# definitions of necessary trees
TEXMFSYSVARDIR=/var/lib/texmf
TEXMFTREES="/usr/share/texmf $TEXMFSYSVARDIR"
FULLTEXMFTREES="$TEXMFTREES /usr/share/texlive/texmf /usr/share/texlive/texmf-dist"

# summary of how this script can be called:
#        * <postinst> `configure' <most-recently-configured-version>
#        * <old-postinst> `abort-upgrade' <new version>
#        * <conflictor's-postinst> `abort-remove' `in-favour' <package>
#          <new-version>
#        * <deconfigured's-postinst> `abort-deconfigure' `in-favour'
#          <failed-install-package> <version> `removing'
#          <conflicting-package> <version>


# Give a name to the first commandline argument
action=$1
trigger=$2

. /usr/share/debconf/confmodule
db_version 2.0

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

dhit_libkpathsea_configured ()
{
    kpsewhich --version >/dev/null 2>&1
}

dhit_build_format ()
{

    tempfile=$(mktemp -p /tmp fmtutil.XXXXXXXX)
    printf "Building format(s) $*.\n\tThis may take some time... "
    if fmtutil-sys "$@" > $tempfile 2>&1 ; then
        rm -f $tempfile
        echo "done."
    else
        exec >&2
        echo
        echo "fmtutil-sys failed. Output has been stored in"
        echo "$tempfile"
        echo "Please include this file if you report a bug."
        echo
        exit 1
    fi
}

run_mtxrun_if_possible()
{
    # code from postinst-tex
    if dhit_libkpathsea_configured; then
        if which mtxrun >/dev/null; then
            # we also have to check that texlive-base is installed
            # and configured, otherwise we cannot be sure that
            # all necessary basic files are present
            #
            # dpkg-query has two defects wrt not existing packages
            # - it is noisy to stderr
            # - it returns 1
            # so shut both errors up
            stat=$(dpkg-query -W -f='${Status}' context 2>/dev/null || true)
            case "$stat" in
                "install ok installed")
                    do_it=1
                    ;;
                *)
                    do_it=0
                    ;;
            esac
            if [ "$do_it" = 1 ] ; then
                tempfile=$(mktemp -p /tmp mtxrun.XXXXXXXX)
                printf "Running mtxrun --generate. This may take some time... "
                if mtxrun --generate > $tempfile 2>&1 ; then
                    rm -f $tempfile
                    echo "done."
                else
                    exec >&2
                    echo
                    echo "mtxrun --generate failed. Output has been stored in"
                    echo "$tempfile"
                    echo "Please include this file if you report a bug."
                    echo
                    exit 1
    	        fi
            fi
        fi
    fi
}

do_triggers() 
{
    # vars used to record what we have done already, not to make
    # it two times
    DONE_FULL_LSR=0
    DONE_MTXRUN=0
    # currently we only support only triggers for updmap.d and
    # hyphen.d changes
    # because all the other calls are quite fast 
    # - call all the update-* scripts (it doesn't hurt)
    # - go through all the triggers and call the respective fmtutil/updmap
    #   calls.

    # in any case call the update-* calls
    update-language
    update-fmtutil
    #
    # the following triggers are reacted upon and in that order:
    # - texmf-lsr: call mktexlsr if present
    # - texmf-lsrfull: call mktexlsr if present
    # - texmf-map: call updmap-sys
    # - texmf-hyphen: if texmf-format hasn't been triggered call 
    #                 fmtutil-sys --byhyphen ...
    case " $trigger " in
        *" texmf-lsrfull "*)
            # code from postinst-tex
            if dhit_libkpathsea_configured; then
                # mktexlsr may not be present
                if which mktexlsr >/dev/null; then
                    tempfile=$(mktemp -p /tmp mktexlsr.XXXXXXXX)
                    printf "Running mktexlsr. This may take some time... "
                    if mktexlsr $FULLTEXMFTREES > $tempfile 2>&1 ; then
                        DONE_FULL_LSR=1
                        rm -f $tempfile
                        echo "done."
                    else
                        exec >&2
                        echo
                        echo "mktexlsr $FULLTEXMFTREES failed. Output has been stored in"
                        echo "$tempfile"
                        echo "Please include this file if you report a bug."
                        echo
                        exit 1
                    fi
                fi
            fi
            if [ $DONE_MTXRUN = 0 ] ; then
                run_mtxrun_if_possible
                DONE_MTXRUN=1
            fi
        ;;
    esac
    # do NOT merge these two cases into one, from dpkg's trigger.txt:
    # Generally each trigger name should be tested for separately, as the
    # postinst will often be called for several triggers at once.
    case " $trigger " in
        *" texmf-lsr "*)
          # only to lsr if we haven't done lsrfull
          if [ $DONE_FULL_LSR = 0 ] ; then
            # code from postinst-tex
            if dhit_libkpathsea_configured; then
                # mktexlsr may not be present
                if which mktexlsr >/dev/null; then
                    tempfile=$(mktemp -p /tmp mktexlsr.XXXXXXXX)
                    printf "Running mktexlsr. This may take some time... "
                    if mktexlsr $TEXMFTREES > $tempfile 2>&1 ; then
                        rm -f $tempfile
                        echo "done."
                    else
                        exec >&2
                        echo
                        echo "mktexlsr $TEXMFTREES failed. Output has been stored in"
                        echo "$tempfile"
                        echo "Please include this file if you report a bug."
                        echo
                        exit 1
                    fi
                fi
            fi
          fi
          if [ $DONE_MTXRUN = 0 ] ; then
              run_mtxrun_if_possible
              DONE_MTXRUN=1
          fi
        ;;
    esac
    # do NOT merge these two cases into one, from dpkg's trigger.txt:
    # Generally each trigger name should be tested for separately, as the
    # postinst will often be called for several triggers at once.
    case " $trigger " in
        *" texmf-map "*) 
         # code from postinst-tex
         if dhit_libkpathsea_configured; then
             if which updmap-sys >/dev/null; then
                    # we also have to check that texlive-base is installed
                    # and configured, otherwise we cannot be sure that
                    # all necessary basic files are present
                    #
                    # dpkg-query has two defects wrt not existing packages
                    # - it is noisy to stderr
                    # - it returns 1
                    # so shut both errors up
                    stat=$(dpkg-query -W -f='${Status}' texlive-base 2>/dev/null || true)
                    case "$stat" in
                        "install ok installed")
                            do_it=1
                            ;;
                        *)
                            do_it=0
                            ;;
                    esac
                    if [ "$do_it" = 0 ] ; then
                        echo "texlive-base is not ready, delaying updmap-sys call" >&2
                    else
                        tempfile=$(mktemp -p /tmp updmap.XXXXXXXX)
                        printf "Running updmap-sys. This may take some time... "
                        # call updmap with --nohash so that no ls-R files
                        # are created in /usr/local/share/texmf/
                        # see bug report #607857
                        # instead of that we call mktexlsr $TEXMFSYSVARDIR 
                        # afterwards. This can be done without checks as
                        # we know that dhit_libkpathsea_configured and
                        # since mktexlsr and updmap are in the same package
                        # and we checked for updmap already
                        if updmap-sys --nohash > $tempfile 2>&1 ; then
                            rm -f $tempfile
                            echo "done."
                            tempfile=$(mktemp -p /tmp mktexlsr.XXXXXXXX)
                            printf "Running mktexlsr $TEXMFSYSVARDIR ... "
                            if mktexlsr $TEXMFSYSVARDIR > $tempfile 2>&1 ; then
                                rm -f $tempfile
                                echo "done."
                            else
                                exec >&2
                                echo
                                echo "mktexlsr $TEXMFSYSVARDIR failed. Output has been stored in"
                                echo "$tempfile"
                                echo "Please include this file if you report a bug."
                                echo
                                exit 1
                            fi
                        else
                            exec >&2
                            echo
                            echo "updmap-sys failed. Output has been stored in"
                            echo "$tempfile"
                            echo "Please include this file if you report a bug."
                            echo
                            echo "Sometimes, not accepting conffile updates in /etc/texmf/updmap.d"
                            echo "causes updmap-sys to fail.  Please check for files with extension"
                            echo ".dpkg-dist or .ucf-dist in this directory" 
                            echo
                            exit 1
    	                fi
                    fi
                fi
            fi
        ;;
    esac
    # do NOT merge these two cases into one, from dpkg's trigger.txt:
    # Generally each trigger name should be tested for separately, as the
    # postinst will often be called for several triggers at once.
    case " $trigger " in
        *" texmf-hyphen "*) 
          if dhit_libkpathsea_configured; then
            if which kpsewhich >/dev/null; then
              if which fmtutil-sys >/dev/null; then
                # code from postinst.tex
                v=$(kpsewhich -var-value TEXMFSYSVAR)
                c=$(kpsewhich -var-value TEXMFSYSCONFIG)
                TEXMFVAR="$v"
                TEXMFCONFIG="$c"
                export TEXMFVAR TEXMFCONFIG
                fmtcnffile=$(kpsewhich --format='web2c files' fmtutil.cnf)
                X=$(grep "^[[:space:]]*latex[[:space:]]" $fmtcnffile || true)
                if [ -n "$X" ] ; then
                  # latex is installed so we can actually try to recreate
                  # formats based on language.dat
                  tempfile=$(mktemp -p /tmp fmtutil.XXXXXXXX)
                  printf "Building latex-based formats --byhyphen $(kpsewhich language.dat).\n\tThis may take some time... "
                  if fmtutil-sys --byhyphen "$(kpsewhich language.dat)" > $tempfile 2>&1 ; then
                    rm -f $tempfile
                    echo "done."
                  else
                    exec >&2
                    echo
                    echo "fmtutil-sys failed. Output has been stored in"
                    echo "$tempfile"
                    echo "Please include this file if you report a bug."
                    echo
                    exit 1
                  fi
                fi
                Y=$(grep "^[[:space:]]*tex[[:space:]]" $fmtcnffile || true)
                if [ -n "$Y" ] ; then
                  # tex is installed so we can actually try to recreate
                  # formats based on language.def
                  tempfile=$(mktemp -p /tmp fmtutil.XXXXXXXX)
                  printf "Building e-tex based formats --byhyphen $(kpsewhich language.def).\n\tThis may take some time... "
                  if fmtutil-sys --byhyphen "$(kpsewhich language.def)" > $tempfile 2>&1 ; then
                    rm -f $tempfile
                    echo "done."
                  else
                    exec >&2
                    echo
                    echo "fmtutil-sys failed. Output has been stored in"
                    echo "$tempfile"
                    echo "Please include this file if you report a bug."
                    echo
                    exit 1
                  fi
                fi
              fi
            fi
          fi
        ;;
    esac
}

ucf_is_changed() {
  file=$1
  if  [ "$(ucfq --with-colons $file | cut -f 4 --delimiter=:)" = "Yes" ] ; then
    # shell return codes are reverted!
    return 0
  else
    return 1
  fi
}

cfgval()
{
  cnfFile="$1"
  opt="$2"
  cat "$cnfFile" | sed -n 's/^'"$opt"'[  =][     =]*//p' | sed q
}


#################################################################
# Here starts the real action
#################################################################


case $action in
    triggered)
        do_triggers
        ;;

    configure|reconfigure)

    # remove old language.dat file, it is not used anymore
    if [ -f /etc/texmf/language.dat ] ; then
        old_ldat_md5sum=`md5sum /etc/texmf/language.dat`
        if [ ! "$old_ldat_md5sum" = fe9baf0768ade79a585a9df568dac5f6 ] && \
            [ ! "$old_ldat_md5sum" = 1d2d9b25a41ab1cec892bd3382af7645 ]; then
            cat > /etc/texmf/language.dat.postinst-bak <<EOF
This file is no longer used and has therefore been renamed by the postinst 
script of the tex-common package.

Please use the mechanism described in update-language(8) instead.

EOF
            cat /etc/texmf/language.dat >> /etc/texmf/language.dat.postinst-bak
        fi
        rm /etc/texmf/language.dat
    fi

    # if we are upgrading from a 1 < version < 3 we do the full upgrade stuff
    # we saved the second argument into $trigger, which contains now 
    # the version
    # using the double check also guarantees that the code is NOT executed
    # on new installs, where $trigger is empty
    if dpkg --compare-versions "$trigger" lt "3" && dpkg --compare-versions "$trigger" gt 1 ; then
        #
        # whatever we do, we remove the updmap.cfg file in /var/lib/texmf/web2c!!
        # it was created by former versions of update-updmap and disturbs the 
        # peace in the new system!
        rm -f /var/lib/texmf/web2c/updmap.cfg

        # purge the old texmf.cnf file
        ucf --purge /etc/texmf/texmf.cnf
        if test -x "`which ucfr`" ; then
            ucfr --purge tex-common /etc/texmf/texmf.cnf
        fi
        # we might have already removed this file on a failed upgrade trial
        rm -f /etc/texmf/texmf.cnf
        rm -f /etc/texmf/texmf.cnf.ucf-new
        rm -f /etc/texmf/texmf.cnf.ucf-old
        rm -f /etc/texmf/texmf.cnf.ucf-dist

        #
        # ucf files that will be removed
        UCF_REMOVE="texmf.d/05TeXMF.cnf texmf.d/15Plain.cnf texmf.d/45TeXinputs.cnf texmf.d/55Fonts.cnf texmf.d/65BibTeX.cnf texmf.d/75DviPS.cnf texmf.d/80DVIPDFMx.cnf texmf.d/85Misc.cnf texmf.d/90TeXDoc.cnf texmf.d/95NonPath.cnf"
        for i in $UCF_REMOVE ; do
            file=/etc/texmf/$i
            if [ -r $file ] ; then
                if ucf_is_changed $file ; then
                    cat > $file.postinst-bak <<EOF
This file is no longer used and has therefore been renamed by the postinst 
script of the tex-common package.
EOF
                    cat $file >> $file.postinst-bak
                fi
                rm $file
                rm -f $file.ucf-old
                rm -f $file.ucf-new
                rm -f $file.ucf-dist
            fi
            ucf --purge $file
            if test -x "`which ucfr`" ; then
                ucfr --purge tex-common $file
            fi
        done

        # move changed settings from 00updmap.cfg to /etc/texmf/web2c/updmap.cfg
        if [ -r /etc/texmf/updmap.d/00updmap.cfg ]; then
            if [ ! -r /etc/texmf/web2c/updmap.cfg ] ; then
                # these are the defaults in tex-common < 3 
                dflt_dvipsPreferOutline=true
                dflt_LW35=URWkb
                dflt_dvipsDownloadBase35=false
                dflt_pdftexDownloadBase14=true
                dflt_dvipdfmDownloadBase14=true
                options="dvipsPreferOutline LW35 pdftexDownloadBase14 dvipdfmDownloadBase14 dvipsDownloadBase35"
                SETTING_CHANGED=false
                tempdir=`mktemp -d`
                tempfile=`mktemp -p $tempdir`
                trap 'cleanup' HUP INT QUIT BUS PIPE TERM
                for option in $options; do
                    eval $option=`cfgval /etc/texmf/updmap.d/00updmap.cfg $option`
                    if eval [ ! "\$$option" = "\$dflt_$option" ]; then
                        # the defaults in tex-common < 3 and TL2012 are the
                        # same with one exception: dvipsDownloadBase35
                        # it was false in tex-common and true in TL2012
                        #
                        if [ ! $option = dvipsDownloadBase35 ] ; then
                            # options agree between TL2012 and tex-common < 3
                            # so move the change over!
                            SETTING_CHANGED=true
                            eval optvalue=\$$option
                            echo "$option = $optvalue" >> $tempfile
                        else
                            # dvipsDownloadBase35 case
                            # in tex-common the default was false
                            # now it is true
                            # since the admin changed it from false -> true
                            # and now it is true anyway, we don't write
                            # anything for this case
                            :
                        fi

                    fi
                done
                if [ "$SETTING_CHANGED" = "true" ]; then
                    mkdir -p /etc/texmf/web2c/
                    mv $tempfile /etc/texmf/web2c/updmap.cfg
                fi
            fi
            rm /etc/texmf/updmap.d/00updmap.cfg
            rm -f /etc/texmf/updmap.d/00updmap.cfg.ucf-old
            rm -f /etc/texmf/updmap.d/00updmap.cfg.ucf-new
            rm -f /etc/texmf/updmap.d/00updmap.cfg.ucf-dist
            ucf --purge /etc/texmf/updmap.d/00updmap.cfg
            if test -x "`which ucfr`" ; then
                ucfr --purge tex-common /etc/texmf/updmap.d/00updmap.cfg
            fi
            # try to remove the now hopefully empty dir
            rmdir --ignore-fail-on-non-empty /etc/texmf/updmap.d 
        fi

    # end of upgrade from versions < 3
    fi    

    # after we have removed the left overs from old times
    # create/update texmf.cnf
    update-texmf

    #
    # call trigger action
    # that calls mktexlsr if possible, and update-*
    # we set the triggers updmap.d
    #
    trigger="texmf-lsr texmf-map"
    do_triggers


    # now call the equivalent of fmtutil-sys --all explicitely
    # we also have to check that texlive-base is installed
    # and configured, otherwise we cannot be sure that
    # all necessary basic files are present
    if dhit_libkpathsea_configured; then
        # see above for information on dpkg-query usage
        stat=$(dpkg-query -W -f='${Status}' texlive-base  2>/dev/null || true)
        case "$stat" in
        "install ok installed")
            do_it=1
            ;;
        *)
            do_it=0
            ;;
        esac
        if [ "$do_it" = 0 ] ; then
            echo "texlive-base is not ready, skipping fmtutil-sys --all call" >&2
        else
            dhit_build_format --all
        fi
    fi


    # create empty dirs in /usr/local/share/
    if [ ! -e /usr/local/share/texmf ]
    then
      if mkdir -p /usr/local/share/texmf 2>/dev/null
      then
        chown root:staff /usr/local/share/texmf
        chmod 2775 /usr/local/share/texmf
      fi
    fi

    # remove out dated dir /etc/texmf/language.d
    if [ -d /etc/texmf/language.d ] ; then 
        rmdir --ignore-fail-on-non-empty /etc/texmf/language.d/
    fi

    ;;
  *)
    ;;
esac


#DEBHELPER#

### Local Variables:
### perl-indent-level: 4
### tab-width: 4
### indent-tabs-mode: nil
### End:
# vim:set tabstop=4 expandtab: #
