#!/bin/sh

################################################################################
#
# Copyright (C) Martem AS 2015
# Author: Mark Tomm
#
################################################################################

start() {
    local STATS_DIR=/var/local/telem/stats
    local TELEM_VAR_DIR=/var/local/telem
    local USR_REBOOT_FILE="${TELEM_VAR_DIR}/user-reboot"
    local WDT_STAT_FILE="${STATS_DIR}/watchdog-boot-message"
    local WDT_APP="/usr/local/bin/imx/getwdbootmsg"
    local WDT_APP_OUTPUT="/tmp/wdt-boot-msg"
    local MSG=""
    
    if [[ -f "${USR_REBOOT_FILE}" ]] ; then
        . "${USR_REBOOT_FILE}"
        [ -z "$rparent" ] && rparent="user"
        MSG="Reboot was issued by $rparent"
        [ -n "$rmsg" ] && MSG="$MSG; $rmsg"
        [ -n "$rargs" ] && MSG="$MSG; $rargs"
        rm "${USR_REBOOT_FILE}" 2>/dev/null
    else
        if [[ -f "${WDT_APP}" ]] ; then
            .${WDT_APP}
            
            if [[ $? = "0" ]] && [[ -f "${WDT_APP_OUTPUT}" ]] ; then
                MSG="$(cat ${WDT_APP_OUTPUT})"
            else
                MSG="${WDT_APP} failed"
            fi
            
        else
            MSG="${WDT_APP} missing"
        fi
    fi
    
    logger -t "$0" "${MSG}"
    if [[ -f "${WDT_STAT_FILE}" ]] && \
    [[ $(wc -l "${WDT_STAT_FILE}" | awk '{print $1}') -gt 20 ]] ; then
        sed -i '1d' "${WDT_STAT_FILE}"
    fi
    
    if [[ -d "${STATS_DIR}" ]]; then
        echo "$(date) ${MSG}" >> "${WDT_STAT_FILE}"
    else
        logger -t "$0" "No such directory ${STATS_DIR}"
    fi
}
stop() {
    echo "Nothing to be done"
    return 0
}
restart() {
    echo "Nothing to be done"
    return 0
}

case "$1" in
  start)
    start
    ;;
  stop)
    stop
    ;;
  restart|reload)
    restart
    ;;
  *)
    echo $"Usage: $0 {start|stop|restart}"
    exit 1
esac

exit $?
