#!/bin/sh
#
# License: Copyright 2015 SpinetiX. 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: 2 3 5
# Default-Stop:
# Short-Description: Starting/stopping SpinetiX's watchdog
# Description: Starting/stopping SpinetiX's watchdog
### END INIT INFO
#

# Init script information
NAME=spxmanage-watchdog
DESC="SPX watchdog"

# watchdog daemon
DAEMON=/usr/sbin/watchdog
TEMPLATECONF=/usr/share/spxmanage/watchdog/watchdog.conf.tmpl
VOLATILECONF=/var/run/spxmanage/watchdog/watchdog.conf
ARGS="-c $VOLATILECONF"
BASENAME=watchdog
PIDFILE=/var/run/$BASENAME.pid

# config
RCMAIN=/usr/share/resources/default/init/main

# The dummy PID file, used by repair binary
# The PID in this file is 1, which always exists
PIDDUMMY=/var/run/watchdog-dummy.pid

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

# Load ancillary configurations
AVAHI_DAEMON_START=1
[ -f /etc/default/avahi-daemon ] && . /etc/default/avahi-daemon 
[ -f /var/run/avahi-autoipd.state ] && . /var/run/avahi-autoipd.state
DISABLE_LLMNRD=
[ -f /etc/default/llmnrd ] && . /etc/default/llmnrd
SNMPDRUN=no
[ -f /etc/default/snmpd ] && . /etc/default/snmpd

# Load resources
[ -f "$RCMAIN" ] && . "$RCMAIN"

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

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

do_watchdog_conf() {
    local iface model revision
    if ! [ -f "$TEMPLATECONF" ]; then
        echo -n "missing configuration file template"
        return 1
    fi
    cat "$TEMPLATECONF" > "$VOLATILECONF".tmpl || return
    if [ "$AVAHI_DAEMON_START" != 1 ]; then
        sed -i -e '/@@AVAHI_DAEMON_START@@/,/@@AVAHI_DAEMON_END@@/d' "$VOLATILECONF".tmpl || return
    fi
    if [ -n "$DISABLE_LLMNRD" ]; then
        sed -i -e '/@@LLMNRD_START@@/,/@@LLMNRD_END@@/d' "$VOLATILECONF".tmpl || return
    fi
    if [ "$SNMPDRUN" != 'yes' ]; then
        sed -i -e '/@@SNMPD_START@@/,/@@SNMPD_STOP@@/d' "$VOLATILECONF".tmpl || return
    fi
    if [ "$rc_has_wlan" != 'yes' ]; then
        sed -i -e '/@@IWD_START@@/,/@@IWD_END@@/d' "$VOLATILECONF".tmpl || return
    fi
    if ! [ -f /var/lib/ead/default.8021x ]; then
        sed -i -e '/@@EAD_START@@/,/@@EAD_END@@/d' "$VOLATILECONF".tmpl || return
    fi
    # Only Fukiran (i.e. HMP400) boards DV5+ (rev Bxxx) and DV5 engineering samples (rev 5001)
    # have the uController and thus start spxucd
    [ -f /sys/class/spx-board-info/id/model ] && \
        model="$(cat /sys/class/spx-board-info/id/model)" || model=
    [ -f /sys/class/spx-board-info/id/revision ] && \
        revision="$(cat /sys/class/spx-board-info/id/revision)" || revision=
    if ! [ -f /run/spxucd/present ]; then
        sed -i -e '/@@SPXUCD_START@@/,/@@SPXUCD_END@@/d' "$VOLATILECONF".tmpl || return
    fi
    if ! [ -x /usr/bin/licensecheck ]; then
        sed -i -e '/@@LICENSECHECK_START@@/,/@@LICENSECHECK_END@@/d' "$VOLATILECONF".tmpl || return
    fi
    if ! [ -x /usr/sbin/mcelog ]; then
        sed -i -e '/@@MCELOG_START@@/,/@@MCELOG_STOP@@/d' "$VOLATILECONF".tmpl || return
    fi

    for iface in $AVAHI_AUTOIPD_IFACES; do
        sed -i -e '/@@AVAHI_AUTOIPD_IFACE@@/{p;s/@@AVAHI_AUTOIPD_IFACE@@/'"$iface"'/;s/^#\s*//}' "$VOLATILECONF".tmpl || return
    done
    mv "$VOLATILECONF".tmpl "$VOLATILECONF" || return 
}

start() {
    local RET
    local f

    # Create the volatile watchdog configuration file
    if ! do_watchdog_conf ; then
        failure; echo
        return 1
    fi

    # Stop any potentially running watchdog daemon first
    if start-stop-daemon -K --quiet --pidfile $PIDFILE; then
        echo -n "Waiting for existing watchdog daemon to exit..."
        sleep 6
        echo
    fi

    # Create the dummy PID file (PID 1 is init, always there)
    echo 1 > "$PIDDUMMY"

    echo -n "Starting $DESC: "
    echo -n "$BASENAME"
    sleep 3 # give a bit of time for daemons to create their PID files
    start-stop-daemon -S --quiet --exec $DAEMON -- $ARGS
    RET=$?
    if [ $RET -eq 0 ]; then
        echo -n ", "
    else
        echo -n " "; failure; echo
        return 1
    fi
        
    echo -n "boot-id "
    cat /proc/sys/kernel/random/boot_id > /var/cache/spxmanage/www/docs/boot-id

    echo -n "led "
    for f in /sys/class/leds/system:green:status /sys/class/leds/*:green:status1; do
        [ -d "$f" ] || continue
        echo heartbeat > "$f"/trigger
    done

    success; echo

    return 0
}

stop () {
    local RET
    local f

    echo -n "Stopping $DESC: "
    echo -n "led, "
    for f in /sys/class/leds/system:green:status /sys/class/leds/*:green:status1; do
        [ -d "$f" ] || continue
        if egrep -q '(^|\s|\[)fixed-timer(\]|\s|$)' "$f"/trigger; then
            echo fixed-timer > "$f"/trigger
        else
            echo timer > "$f"/trigger
            echo 62 > "$f"/delay_on
            echo 63 > "$f"/delay_off
        fi
    done

    echo -n "sync"
    sync
    RET=$?
    if [ $RET -eq 0 ]; then
        echo -n ", "
    else
        echo -n " failed, "
    fi
    echo -n "$BASENAME"
    start-stop-daemon -K --quiet --pidfile $PIDFILE
    RET=$?
    if [ $RET -eq 0 ]; then
        echo -n ". The device will hard reboot if no watchdog daemon is restarted within 1 min. "
        success; echo
    else
        echo -n " "
        failure; echo
        return 1
    fi

    return 0
}

restart() {
    local RET

    echo "Restarting $DESC..."
    stop
    sleep 6
    start
    RET=$?

    return $RET
}

condrestart() {
    local RET

    pidofproc $BASENAME >/dev/null
    RET=$?
    if [ $RET -eq 0 ]; then
        restart
        RET=$?
    else
        RET=1
    fi

    return $RET
}

reload() {
    local RET

    echo -n "Reloading $DESC configuration not supported "
    failure

    return 1
}

forcereload() {
    local RET

    reload
    RET=$?
    if [ $RET -ne 0 ]; then
        restart
        RET=$?
    fi
        
    return $RET
}

parse() {
    case "$1" in
        start)
            start
            return $?
            ;;
        stop)
            stop
            return $?
            ;;
        restart)
            restart
            return $?
            ;;
        condrestart|try-restart)
            condrestart
            return $?
            ;;
        reload)
            reload
            return $?
            ;;
        force-reload)
            forcereload
            return $?
            ;;
        status)
            status $BASENAME
            return $?
            ;;
        *)
            echo "Usage: $NAME " \
                "{start|stop|restart|condrestart|reload|force-reload|status}" >&2
            ;;
    esac
        
    return 1
}

parse $@

