#!/bin/sh
###############################################################
# This script will execute system startup ('S') scripts.
#
# Author: Dragan Marinkovic <dmarinkovi@sierrawireless.com>
#
# Copyright (C) Sierra Wireless, Inc
###############################################################

# Import runtime environment
source /etc/run.env

# The name of this script
this_e=$( basename $0 )

# The script of control msm_watchdog
CONTROL_WDT=/etc/init.d/control_msm_watchdog.sh
if [ ! -x ${CONTROL_WDT} ] ; then
    # If the script is not present, use /bin/false instead to have a failed return code
    # but do not stop the rcS script as it considered as a minor error.
    CONTROL_WDT="/bin/false"
fi

#
# Helper functions
#

#
# Mount essential file systems
#
mount_essential_fs()
{
    local ret=0

    if [ -e /proc/cmdline ]; then
        return ${ret}
    fi

    # Mount proc file system
    mount -t proc proc /proc -o smackfsdef=_

    # Mount sysfs file system
    mount -t sysfs sysfs /sys

    # mount debugfs
    mount -t debugfs debugfs /sys/kernel/debug

    return ${ret}
}

simple_network()
{
    local ret=0

    ifconfig lo up

    return ${ret}
}

# Execute 'S' scripts. This method will not execute scripts
# which are not executable.
run_S_scripts()
{
    local ret=0
    local log_level=$kern_debug
    local root_path=""
    local file=""

    # Execute all 'S' scripts. It is assumed that 'S' scripts
    # are soft links to the executable scripts elsewhere.
    for s in ${root_path}/etc/rcS.d/S* ; do
        file=$( realpath ${s} )
        if [ -x ${file} ] ; then
            kern_log $log_level "LE_KPI: start initscript %s\n" ${s}
            ${s} start
            kern_log $log_level "LE_KPI: end initscript %s\n" ${s}
            # Kick MSM_WATCHDOG one time.
            ${CONTROL_WDT} kick
        else
            echo "${this_e}: Not starting ${s}, it is not executable."
        fi
    done

    # By default, kernel doesn't kick MSM_WATCHDOG durning bootup automatically.
    # During system startup, we need to kick WDT when every rcS script is done to
    # protect module out of stuck. When system has started ok, we need to set barktime
    # back to 11s and start to kick MSM_WATCHDOG in kernel.
    ${CONTROL_WDT} setbarktime 11
    ${CONTROL_WDT} startautokick

    return ${ret}
}

#
# Main method
#
rcS_main()
{
    local ret=0

    # list of methods to execute
    local method_list="
                       mount_essential_fs
                       simple_network
                       run_S_scripts
                      "

    for method in ${method_list} ; do
        echo "${this_e}: Executing ${method}... "
        ${method}
        if [ $? -ne 0 ] ; then return 1 ; fi
    done

    return ${ret}
}

#
# The execution starts here.
#
rcS_main
if [ $? -ne 0 ] ; then
    echo "System error! "
    exit 1
fi
