#!/bin/bash
#
# description: NorCal system init script

# This script is written as a bash script, calling /usr/bin/NorCalInit
# to do all of the real work, so that we can use the existing code to
# print 'OK'/'FAIL' at bootup time.

# The NorCal is started fairly early in the boot process, between the
# two stages of Eos initialization.

. /etc/rc.d/init.d/functions

REDUNDANCY_FILE="/var/run/redundancy-protocol"

start() {
    echo -n $"Starting NorCal initialization: "
    # Redirect stdin to prevent NorCalInit from dropping into the debugger on failure
    if /usr/bin/NorCalInit </dev/null >>/var/log/NorCalInit 2>&1; then
        # print redundancy status
        if [ -f $REDUNDANCY_FILE ]; then
            PROTOCOL="`cat $REDUNDANCY_FILE | grep ^REDUNDANCY_PROTOCOL | cut -d '=' -f 2`"
            echo -n "Redundancy protocol is $PROTOCOL. "
        fi
        success
        echo
    else
        # If NorCalInit fails, the system is pretty much hosed
        failure
        # Sometimes box resets again post NorCalInit failure, resulting in contents
        # of /var/log/NorCalInit to be lost. We copy /var/log/NorCalInit to
        # /mnt/flash/debug in the systemd unit (see NorCal.service/OnFailure).
        echo
        echo $"   (errors in /var/log/NorCalInit and /mnt/flash/debug/NorCalInit; log in as 'root' to troubleshoot)"
        exit 1
    fi
}

# Once we figure out what it means to "stop" NorCal, add support to do
# that here.
case "$1" in
start)
    start
    ;;
stop)
    ;;
*)
    echo $"Usage: $0 {start}"
    exit 1
esac
