#!/bin/bash
#
# License: Copyright 2020 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 IoT services daemon
# Description: Starting/stopping SpinetiX's IoT services daemon
### END INIT INFO

# Init script information
NAME=mcelog
DESC="Machine check exception decoder"

# Individual Daemon information
DAEMON=/usr/sbin/mcelog
ARGS="--syslog --no-dmi --daemon"
BASENAME=mcelog

PIDFILE=/run/mcelog.pid

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

start() {
    local RET ERROR=

    echo -n "Starting $DESC: "

    echo -n "$NAME "

    $DAEMON $ARGS
    RET=$?
    if [ $RET -eq 0 ]; then
        success; echo
    else
        failure; echo
        return 1
    fi

    return 0
}

stop() {
    local RET ERROR=

    echo -n "Stopping $DESC: $NAME "
    kill "$(< $PIDFILE)"

    RET=$?
    if [ $RET -eq 0 ]; then
        success; echo
    else
        failure; echo
        return 1
    fi

    return 0
}

restart() {
    local RET

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

    return $RET
}

decode_mce() {
    dmesg | grep 'mce:\s*\[' | mcelog --ascii 2>/dev/null | logger -t mcelog
}

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

    return 1
}

parse $@
