#!/bin/bash
#
# This script installs a GBK TrueType font for use by CCT and CJK
#
# The script installs files in $TEXMFMAIN if run by root,
# $HOMETEXMF if run by a non root user, or $texmf if it's defined
#
# Author: zlb, 2004/12/05
#

canonicalize () {
    # ׼ļ "$1" (е ., .. ͷӲתɾ·)
    local path dir d0 d target		# ֲ

    if [ $# -ne 1 ]; then
	echo 1>&2 "Usage: canonicalize pathname"
	return 1
    fi

    path="$1"				# ļ
    if test "${path#/}" = "$path"; then path="`pwd`/$path"; fi
					# תɾ·
    
    # һɨ裺ȥ
    dir=""
    # ļеÿĿ¼ѭ (ΪļеĿո񣬽'#')
    for d in `echo "$path" | sed -e 's/ /#/g' -e 's/\// /g'`; do
	d="`echo $d|sed -e 's/#/ /g'`"	#  '#' ؿո
	d0="$dir"			# ǰĿ¼
	dir="$dir/$d"			# һĿ¼
	while test -h "$dir"; do
	    # 滻
	    target=`/bin/ls -l "$dir" | awk -F' -> ' '{print $2}'`
	    if test "${target#/}" != "$target"; then
		dir="$target"		# ĿǾ·
	    else
		dir="$d0/$target"	# Ŀ·
	    fi
	    d0="${dir%/${dir##*/}}"	# µĵǰĿ¼
	done
    done
    path="$dir"
    
    # ڶɨ裺ȥ "."  ".."
    dir=""
    for d in `echo "$path" | sed -e 's/ /#/g' -e 's/\// /g'`; do
	d="`echo $d | sed -e 's/#/ /g'`"
	case "$d" in
	    ..) dir="${dir%/[^/]*}" ;;
	    .)	continue ;;
	    *)	dir="$dir/$d" ;;
	esac
    done
    path="$dir"				# pathаմ

    echo $path
}

import_cfg () {
    # import a configuration file from the LOCAL/MAIN TEXMF tree to $TEXMF
    mkdir -p $texmf/$1 || exit 1
    if ! test -r $texmf/$1/$2; then
	# Check texmflocal
	if test -r $texmflocal/$1/$2; then
	    echo 1>&2 "Importing $texmflocal/$1/$2 to $texmf/$1/$2"
	    /bin/cp -p $texmflocal/$1/$2 $texmf/$1 || exit 1
	else
	    # Check texmfmain
	    if test -r $texmfmain/$1/$2; then
		echo 1>&2 "Importing $texmfmain/$1/$2 to $texmf/$1/$2"
		/bin/cp -p $texmfmain/$1/$2 $texmf/$1 || exit 1
	    fi
	fi
    fi
    echo 1>&2 "Updating $texmf/$1/$2 ..."
    return 0
}

force=0
texmfmain=`kpsewhich --expand-path='$TEXMFMAIN'`
texmflocal=`kpsewhich --expand-path='$TEXMFLOCAL'`
hometexmf=`kpsewhich --expand-path='$HOMETEXMF'`

test -z "$texmfmain" && texmfmain="/usr/share/texmf"
test -z "$hometexmf" && hometexmf="${HOME}/texmf"

if test -z "$texmf"; then
    if [ "`/usr/bin/id -u`" = 0 ]; then
	texmf="$texmfmain"
    else
	texmf="$hometexmf"
    fi
fi

if [ "$1" = "-f" ]; then
    force=1
    shift
fi

if [ "$1" = list ]; then
    if test -x $texmfmain/tex/cct; then
	echo 1>&2 "GBK fonts installed in $texmfmain:"
	cd $texmfmain/tex/cct >/dev/null 2>&1 && \
	    ls gbk*.fon | sed -e 's/\.fon//g' -e 's/^/  /'
    fi
    if test -x $HOME/texmf/tex/cct; then
	echo 1>&2 "GBK fonts installed in $HOME/texmf/tex/cct:"
	cd $HOME/texmf/tex/cct >/dev/null 2>&1 && \
	    ls gbk*.fon | sed -e 's/\.fon//g' -e 's/^/  /'
    fi
    exit 0
fi

if [ $# -ne 2 ]; then
    cat 1>&2 <<END
Usage:

. To install a GBK font (use option '-f' to force installing a font)
    $0 [-f] filename.ttf gbkname

. To remove a GBK font
    $0 remove gbkname

. To list GBK fonts installed
    $0 list

Example:
    $0 /usr/share/fonts/zh_CN/TrueType/gbsn00lp.ttf song
    
To specify an alternate installation path, set the variable 'texmf', e.g.:
    env texmf=/usr/local/share/texmf $0 filename.ttf gbkname

will install in "/usr/local/share/texmf".
END
    exit 1
fi

umask 022
ttfname="$1"
gbkname="gbk${2#gbk}"

# Check if $texmf is writable
if test -d "$texmf" -a ! -w "$texmf" || test -f "$texmf" ; then
    echo 1>&2 "Error: $texmf is not a writable directory!"
    exit 1
fi

if [ "$ttfname" = remove ]; then
    echo 1>&2 "Removing font $gbkname in $texmf ..."
    tempfile=/tmp/gbkfont-inst-temp.$$
    #map=$texmf/dvips/config/cjk.map
    map=$texmf/fonts/map/dvips/CJK/cjk.map
    mkdir -p `dirname $map`
    if test -r $map; then
	grep -v "^$gbkname"'\(\|sl\)[0-9][0-9] ' $map >$tempfile
	/bin/cp -f $tempfile $map
	/bin/rm -f $tempfile
    fi
    # Note: leave 'p +cjk.map' line in config.ps
    # Note: leave 'dvipsmap cjk.map' in xdvi.cfg
    # Note: leave 'map +cjk.map' in pdftex.cfg
    #map=$texmf/dvipdfm/config/cid-x.map
    map=$texmf/fonts/map/dvipdfm/dvipdfmx/cid-x.map
    mkdir -p `dirname $map`
    if test -r $map; then
	grep -wv "${gbkname}"'\(\|sl\)@UGBK@' $map >$tempfile
	/bin/cp -f $tempfile $map
	/bin/rm -f $tempfile
    fi
    #map=$texmf/ttf2pk/ttfonts.map
    map=$texmf/fonts/map/ttf2pk/ttfonts.map
    mkdir -p `dirname $map`
    if test -r $map; then
	grep -wv "${gbkname}"'\(\|sl\)@UGBK@' $map >$tempfile
	/bin/cp -f $tempfile $map
	/bin/rm -f $tempfile
    fi
    /bin/rm -rf "$texmf/dvips/chinese/$gbkname"
    /bin/rm -rf "$texmf/fonts/afm/chinese/$gbkname"
    /bin/rm -rf "$texmf/fonts/tfm/chinese/$gbkname"
    /bin/rm -rf "$texmf/fonts/type1/chinese/$gbkname"
    /bin/rm -f  "$texmf/tex/latex/CJK/GB/c19${gbkname#gbk}.fd"
    /bin/rm -f  "$texmf/tex/cct/${gbkname}.fon"
    /bin/rm -f  "$texmf/tex/cct/${gbkname}.tbl"
    # For teTeX-3: remove entries in pdftex.map
    map=`kpsewhich -format=map pdftex.map`
    if test -n "$map"; then
	grep -v "^$gbkname"'\(\|sl\)[0-9][0-9] ' $map >$tempfile
	/bin/cp -f $tempfile $map
	/bin/rm -f $tempfile
    fi
    texhash >/dev/null 2>&1
    exit 0
fi

#----------------------------------------------------------------------------

# check whether filesystem is vfat or ntfs
ttfname=`canonicalize "$1"`
echo 1>&2 "gbkfont-inst: canonicalized ttfname = $ttfname"

# check for Windows filesystem
###dir="`dirname $ttfname`"
###mnt="`df -t vfat -t ntfs $dir | grep -v '^Filesystem ' | awk '{print $6}'`"
###if test -n "$mnt" && test "${ttfname#$mnt}" != "$ttfname"; then
###    # only lowercase starting from the mount point
###    ttfname="`echo $ttfname | awk '{i=length("'$mnt'")
###		if (i > 0) printf "%s%s", "'$mnt'", tolower(substr($0,i+1))
###		else print}'`"
###    echo 1>&2 "gbkfont-inst: DOS/Windows fs, ttfname = $ttfname"
###fi

# First, make sure the TrueType font exists
if ! test -r "$ttfname"; then
    echo 1>&2 "Error: cannot open TrueType font $ttfname"
    exit 1
fi

echo 1>&2 "Installing font $gbkname in $texmf ..."

if [ $force = 0 -a -r "$texmf/tex/cct/${gbkname}.fon" ]; then
    echo 1>&2 "Font $gbkname already installed."
    exit 0
fi

tempdir=/tmp/gbkfonts.$$
tempfile=${tempdir}/tmp
curdir=`pwd`
trap "/bin/rm -rf $tempdir" 0 1 2 3 15
mkdir -p $tempdir
cd $tempdir

gbkfonts $GBKFONTS_OPTS "$ttfname" "${gbkname#gbk}" || exit 1

#--- dvips
#d=dvips/config
d=fonts/map/dvips/CJK
# remove symlink created by older version of CJK-GBKfonts.rpm
test -L $texmf/$d && rm -f $texmf/$d
mkdir -p $texmf/$d
import_cfg $d cjk.map
grep -v "^$gbkname"'\(\|sl\)[0-9][0-9] ' $texmf/$d/cjk.map >$tempfile
/bin/cp -f $tempfile $texmf/$d/cjk.map
/bin/rm -f $tempfile
cat cjk.map >> $texmf/$d/cjk.map

# For teTeX-3: remove entries in pdftex.map
map=`kpsewhich -format=map pdftex.map`
if test -n "$map"; then
    grep -v "^$gbkname"'\(\|sl\)[0-9][0-9] ' $map >$tempfile
    /bin/cp -f $tempfile $map
    /bin/rm -f $tempfile
    cat cjk.map >> $map
fi

import_cfg dvips/config config.ps
if ! grep -q '^p +cjk.map *$' $texmf/dvips/config/config.ps 2>/dev/null; then
    echo 'p +cjk.map' >>$texmf/dvips/config/config.ps
fi

#--- xdvi
import_cfg xdvi xdvi.cfg
if ! grep -q '^dvipsmap cjk.map *$' $texmf/xdvi/xdvi.cfg 2>/dev/null; then
    echo 'dvipsmap cjk.map' >>$texmf/xdvi/xdvi.cfg
fi

#--- updmap.cfg
import_cfg web2c updmap.cfg
if test -r $texmf/web2c/updmap.cfg; then
    if ! grep -qi '^map *cjk.map *$' $texmf/web2c/updmap.cfg 2>/dev/null
    then
	echo "Map cjk.map" >>$texmf/web2c/updmap.cfg
    fi
    ###updmap-sys >/dev/null 2>&1 || updmap >/dev/null 2>&1
fi

#--- pdftex
import_cfg pdftex/config pdftex.cfg
#if ! grep -q '^map +'"$gbkname"'.map *$' $texmf/pdftex/config/pdftex.cfg \
#	2>/dev/null; then
#    echo "map +${gbkname}.map" >>$texmf/pdftex/config/pdftex.cfg
#fi
if ! grep -q '^map +cjk.map *$' $texmf/pdftex/config/pdftex.cfg 2>/dev/null
then
    echo "map +cjk.map" >>$texmf/pdftex/config/pdftex.cfg
fi

#--- dvipdfm
#d=dvipdfm/config
d=fonts/map/dvipdfm/dvipdfmx
# remove symlink created by older version of CJK-GBKfonts.rpm
test -L $texmf/$d && rm -f $texmf/$d
mkdir -p $texmf/$d
import_cfg $d cid-x.map
if [ -r $texmf/$d/cid-x.map ]; then
    egrep -v `awk '{printf "%s|", $1}' cid-x.map | sed -e 's/|$//'` \
	$texmf/$d/cid-x.map >$tempfile
    /bin/cp -f $tempfile $texmf/$d/cid-x.map
    /bin/rm -f $tempfile
fi
cat cid-x.map >> $texmf/$d/cid-x.map

#--- ttf2pk
#d=ttf2pk
d=fonts/map/ttf2pk
mkdir -p $texmf/$d
import_cfg $d ttfonts.map
if [ -r $texmf/$d/ttfonts.map ]; then
    egrep -v `awk '{printf "%s|", $1}' ttfonts.map | sed -e 's/|$//'` \
	$texmf/$d/ttfonts.map >$tempfile
    /bin/cp -f $tempfile $texmf/$d/ttfonts.map
    /bin/rm -f $tempfile
fi
cat ttfonts.map >> $texmf/$d/ttfonts.map

#
d="$texmf/fonts/enc/dvips/chinese"
echo 1>&2 "Copying enc files to $d/$gbkname ..."
mkdir -p $d
/bin/cp -af dvips/chinese/$gbkname $d

#
for d in afm tfm type1; do
    echo 1>&2 "Copying $d files to $texmf/fonts/${d}/chinese/$gbkname ..."
    mkdir -p $texmf/fonts/${d}/chinese
    /bin/cp -af fonts/${d}/chinese/$gbkname $texmf/fonts/${d}/chinese/.
done

# update c19*.fd file
fd="c19${gbkname#gbk}.fd"
# rename existing fd file (texlive provides a broken c19song.fd file)
while true; do
    fd_old="`kpsewhich $fd`"
    test -z "$fd_old" && break
    if test -r "$fd_old"; then
	echo 1>&2 "Note: rename existing \"$fd_old\" as \"$fd_old.bak\"."
	/bin/mv -f "$fd_old" "$fd_old.bak"
    fi
done
echo "Installing $texmf/tex/latex/CJK/GB/$fd ..."
mkdir -p $texmf/tex/latex/CJK/GB
sed -e 's/\\DeclareFontFamily{C19}{\(.*\)}{}/\\DeclareFontFamily{C19}{\1}{\\hyphenchar \\font\\m@ne}/' tex/latex/CJK/GB/$fd >$texmf/tex/latex/CJK/GB/$fd

cd $curdir

# FIXME: tetex does not refresh the filenames database for newly created files
# as a workaround we copy it to CWD
###/bin/cp -f ${tempdir}/tex/latex/CJK/GB/$fd .
###touch ${gbkname}.fon

mkdir -p "$texmf/tex/cct"
touch "$texmf/tex/cct/${gbkname}.fon"
texhash >/dev/null 2>&1

# Run GBKpunct (if available) to create the .tbl file
echo 1>&2 "Running GBKpunct to generate $texmf/tex/cct/${gbkname}.tbl ..."
if GBKpunct $gbkname >"$texmf/tex/cct/${gbkname}.tbl"; then
    texhash >/dev/null 2>&1
fi

#mktexupd="`kpsewhich --format='web2c files' mktexupd`"
#if test -x "$mktexupd"; then
#    $mktexupd $texmf tex/latex/CJK/GB/c19${gbkname#gbk}.fd
#    $mktexupd $texmf tex/cct/${gbkname}.fon
#fi

if test -w "$texmfmain/web2c/texmf.cnf"; then
    echo 1>&2 "Updating $texmfmain/web2c/texmf.cnf ..."
    # change '/' to '\/' for use in R.E.
    dir=`dirname $ttfname | sed -e 's/\\//\\\\\\//g'`
    awk 'BEGIN {ttfpath="'"`dirname $ttfname`"'"}
    {
	if (!match($0, /[ \t]*TTFONTS[ \t]*=/)) {
	    print
	} else {
	    i = index($0, "=")
	    if (i <= 0) {
		print
	    } else {
		s = substr($0, i + 1)
		i = match(s, /(^|;| |\t)'"$dir"'\/\/(;| |\t|$)/)
		if (i > 0) {
		    print
		} else {
		    gsub(/[ \t]*$/, "")
		    printf "%s;%s//\n", $0, ttfpath
		}
	    }
	}
    }' $texmfmain/web2c/texmf.cnf >$tempfile
    /bin/cp -f $tempfile $texmfmain/web2c/texmf.cnf
    /bin/rm -f $tempfile
else
    cat <<END 2>&1
*******************************************************************************
Notice: you may need to manually add the directory:
    `dirname $ttfname`
to the variable '\$TTFONTS' in the file:
    $texmfmain/web2c/texmf.cnf
*******************************************************************************
END
fi

echo 1>&2
echo 1>&2 "You may need to run 'updmap-sys' or 'updmap' after" \
		"installing the fonts."
echo 1>&2

/bin/rm -rf $tempdir

exit 0
