#! /bin/sh
#
# Name: msttcorefonts
# Date: 2007-10-23
# Author: SpinetiX
# Copyright: Copyright 2015 SpinetiX.
# License: 2007 (c) SpinetiX S.A. This file is licensed
#          under the terms of the GNU General Public License version 2.
#          This program is licensed "as is" without any warranty of any
#          kind, whether express or implied.
#
# Copyright 1999-2003 MontaVista Software, Inc.
# Copyright 2002, 2003, 2004 Sony Corporation
# Copyright 2002, 2003, 2004 Matsushita Electric Industrial Co., Ltd.
#
### BEGIN INIT INFO
# Required-Start: 
# Required-Stop:
# Should-Start:
# Should-Stop:
# Default-Start: 
# Default-Stop: 
# Short-Description: unpackage core fonts for the web
# Description: unpackage core fonts for the web
### END INIT INFO 

# Init script information
NAME=msttcorefonts
DESC="core fonts"

# Constants
SYSFONTDIR=/usr/share/fonts
COREFONTDIR="$SYSFONTDIR"/msttcorefonts
FONTPKGDIR=/usr/share/msttcorefonts
TSFILE="$COREFONTDIR"/timestamp
FCCACHE=/usr/bin/fc-cache

# Load init script configuration
[ -f /etc/default/$NAME ] && . /etc/default/$NAME

# Source the init script functions
. /etc/init.d/functions

unpack() {
    local p f bf blf
    rm -rf "$COREFONTDIR"/*.{TTF,ttf}
    for p in "$FONTPKGDIR"/*.exe; do
	7za e -y -aoa -o"$COREFONTDIR" "$p" '*.TTF' '*.ttf' > /dev/null
    done
    for f in "$COREFONTDIR"/*.{TTF,ttf}; do
	bf="${f##*/}"
	blf="$(echo "$bf" | tr '[A-Z]' '[a-z]')"
	[ "$blf" = "$bf" ] || mv "$COREFONTDIR"/"$bf" "$COREFONTDIR"/"$blf"
    done
}

start() {
    local RET

    local run_fccache=

    if [ ! -f "$TSFILE" ]; then
	echo -n "Starting $DESC: "
	echo -n "unpacking"
	unpack
	RET=$?
	if [ $RET -eq 0 ]; then
	    echo -n ", "
	    touch "$TSFILE"
	else
	    echo -n " "; failure; echo
	    return 1
	fi
	run_fccache="yes"
    fi
	
    if [ -x "$FCCACHE" -a "$run_fccache" = "yes" ]; then
	echo -n "updating fc-cache "
	# NOTE: we need to run fc-cache on the parent system font dir
	# for the cache to completely catch the fonts.
	"$FCCACHE" -s "$SYSFONTDIR"
	RET=$?
	if [ $RET -eq 0 ]; then
	    success; echo
	else
	    failure; echo
	    return 1
	fi
    fi

    return 0
}

parse() {
    case "$1" in
	start|restart)
	    start
	    return $?
	    ;;
	stop)
	    return 0
	    ;;
	*)
	    echo "Usage: $NAME {start|restart|stop}" >&2
	    ;;
    esac

    return 1
}

parse $@

