#!/bin/sh
#
# License: Copyright 2015 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 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: S
# Default-Stop:
# Short-Description: Handles splash screen
# Description: Handles splash screen
### END INIT INFO

# NOTE: this script must be started after udev is running or /dev is
# set up, otherwise we may be missing the necessary devices.  It is
# also assumed that sysfs has been already mounted. Also, modutils
# must have been initialized and any necessary kernel modules auto
# loaded.

# Init script information
NAME=splash
DESC="splash screen"

# Defaults
BOOTIMG=
SHUTDOWNIMG=

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

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

# Constants
SYSFSNODE=/sys/class/graphics/fb0
WINCTL=$SYSFSNODE/device/win_ctl
DFBG=/usr/bin/dfbg
DAEMON=/usr/sbin/splashd
ARGS="-w"
FBDEV=/dev/fb/0

use_fbdev() {
    # When the frame buffer is available use that instead of the daemon
    [ -c "$FBDEV" ]
}

has_daemon() {
    use_fbdev && [ -x "$DFBG" ] || [ -x "$DAEMON" ]
}

# Verify daemons are installed
if [ ! has_daemon -a "$1" != "stop" ]; then
    echo -n "Not starting $DESC $NAME, $DAEMON not installed"
    warning
    echo
    exit 0
fi

load_splash() {
    if use_fbdev; then
	$DFBG --dfb:fbdev=$FBDEV,quiet,no-vt $1 2>/dev/null
	if [ -f $WINCTL ]; then
	    echo "osd0 on" > $WINCTL
	    echo "vid0 off" > $WINCTL
	    echo "osd1 off" > $WINCTL
	    echo "vid1 off" > $WINCTL
	fi
    else
	$DAEMON $ARGS "$1"
    fi
    return 0
}

run() {
    local RET ERROR=

    echo -n "$NAME: $2 "
    load_splash "$1"
    RET=$?
    if [ $RET -eq 0 ]; then
	success; echo
    else
	failure; echo
    fi
    return $RET
}

# returns zero if in configuration reset mode
in_config_reset() {
    egrep -q '(^| )config=reset($| )' /proc/cmdline && return 0
    [ -s /boot-config ] && grep -q '^reset$' /boot-config && return 0
    return 1
}

# loads the factory configuration
load_factory_config() {
    . /etc/default/$NAME.spxsave
}

case "$1" in
    start)
	in_config_reset && load_factory_config
	[ -n "$BOOTIMG" ] && run "$BOOTIMG" "Bootup splash image"
	exit $?
	;;
    restart)
	# do nothing, compatibility with update-rc.d
	exit 0
	;;
    stop)
	[ -n "$SHUTDOWNIMG" ] && run "$SHUTDOWNIMG" "Shutdown splash image"
	exit $?
	;;
    updating)
	[ -n "$FIRMUPDIMG" ] && run "$FIRMUPDIMG" "Fimware update splash image"
	exit $?
	;;
    *)
	echo "Usage: $NAME {start|stop|updating|restart}" >&2
	exit 1
	;;
esac
