#!/bin/sh
#
# License: Copyright 2010 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: Sets video modes
# Description: Sets video modes
### END INIT INFO
# chkconfig: S 5 1

# 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.

# Init script information
INIT_NAME=splash
DESC="Splash screen"

# Defaults
BOOTIMG=
SHUTDOWNIMG=

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

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

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

load_splash() {
    if [ -c "$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
	$DAEMON1 $ARGS1 "$1"
    fi
    return 0
}

run() {
    local RET ERROR=

    log_status_msg "$2" -n
    load_splash "$1"
    RET=$?
    if [ $RET -eq 0 ]; then
	log_success_msg "."
    else
	log_failure_msg "failed ($RET: $ERROR), " -n
    fi
    log_status_msg ""
    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/$INIT_NAME.spxsave
}

case "$1" in
	start)
	    in_config_reset && load_factory_config
	    [ -n "$BOOTIMG" ] && run "$BOOTIMG" "Bootup splash image"
	    exit $?
	    ;;
	stop)
	    [ -n "$SHUTDOWNIMG" ]&& run "$SHUTDOWNIMG" "Shutdown splash image"
	    exit $?
	    ;;
	updating)
	    [ -n "$FIRMUPDIMG" ]&& run "$FIRMUPDIMG" "Fimware update splash image"
	    exit $?
	    ;;
	*)
		echo "Usage: $INIT_NAME {start|stop|updating}" >&2
		exit 1
		;;
esac
