#!/bin/sh

# rcS starts functions according to /etc/rc.d/Sxx* or stops functions according to /etc/rc.d/Kxx*
#
# This rcS support 1 signal:
#   1) USR1 to signal that a command has been put into the command pipe.
#
# The command pipe is stored in "commandPipe" variable defined in "/etc/init.d/rc.config"
# The command to send into the pipe has the following format:
# [ALRM|USR1|USR2]
# The current commands are:
#   activate_sm
#   deactivate_sm
#   $startSMCommand
# NOTE: each command has to be a function

############
# CHANGELOG
#===========
# 2013/04/26    crms00432847    Ziming Xu
#               [Blocked]: VHE blocked in step 2 during Network setup
# 2013/03/05    crms00423479    Jerry ZHOU
#               [Regression] No prompt when no Ethernet link in Step2 and VHE stops at 2.5 usb load stage.
# 2013/01/14    PR261951        Jerry ZHOU
#               Reduce time of unavailability during boot time
# 2012/05/04    CRMS00372430    Dongyun Wang
#               Workaround for BT noise
# 2010/03/25    CRMS00221778    Thanh lam NGUYEN
#               Add reboot before entering a step if needed.
#
################

grandtime=$(udate)
/sbin/ldconfig

################################
# CONFIGURATION CONST & VAR
####################################################################@BEGIN FOLD@
# get rc scripts config
source /etc/init.d/rc.config

#PR261951 jerryzh+
# get rc scripts group definition
source /etc/init.d/rc.define
#PR261951 jerryzh-

# CONSTS
#-------
OK="OK" NOK="NOK"
pidFile=/var/run/rcS.pid
defaultLogfile=/tmp/log.rcS
waittime=100000 # in microseconds
profile=/etc/profile
rcDir=/etc/rc.d

#PR261951 jerryzh+
presentation_ready_flag=/tmp/.presentation_ready_flag
#PR261951 jerryzh-

step1label="step 1 - system initialisation"
step2label="step 2 - network setup"
step3label="step 3 - config download"
step4label="step 4 - software upgrade"
step5label="step 5 - run applications"

# VARS
#-----
#PR261951 jerryzh+
step=1 substepinit=0 substep=$substepinit am_status=0
#PR261951 jerryzh-
####################################################################@END FOLD@

################################
# LOG MANAGMENT
####################################################################@BEGIN FOLD@
# The following line is needed if to bypass the "startLog" without problem
exec 3<&0

# startLog
#---------
# Append stdout and stderr output to the logfile given as argument.
# stdout and stderr are redirected until the function endLog is called or the scripts exits.
# if no argument is given the default log file is used.
startLog() {
    local -
    : "${attr:=$esc[0m}startLog $*${default:=$esc[0m}"              # to restore gvim highlight "]}]}"
    local RET=0

    OUTPUT_LOG=${1:-$defaultLogfile}
    OUTPUT_PIPE=/tmp/rcsout.pipe

    [ -e $OUTPUT_PIPE ] && rm -rf $OUTPUT_PIPE >/dev/null 2>&1
    mkfifo $OUTPUT_PIPE

    exec 3<&-
    : "${attr}backup stdin in fd3, stdout in fd4 and stderr in fd5${default}"
    #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    exec 3<&0 4>&1 5>&2
    : "${attr}launch the tee to copy to the log${default}"
    #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    tee $OUTPUT_LOG <$OUTPUT_PIPE >&4 &
    teePid=$!
    : "${attr}from now, all default stdout and default stderr are logged${default}"
    #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    exec 1>$OUTPUT_PIPE 2>&1
    : "${attr}startLog end${default}"
    return $RET
}

# endLog
#-------
# Stop the redirections started with startLog
endLog() {
    local -
    : "${attr:=$esc[0m}endLog $*${default:=$esc[0m}"                # to restore gvim highlight "]}]}"
    local RET=0

    : "${attr}close stdout && stderr${default}"
    echo ""; exec 1>&- 2>&-
    # BUG FIX: normally the previous line should end the tee
    kill $teePid
    unset teePid
    : "${attr}restore default stdin, stdout, stderr and close their backup${default}"
    exec 0<&3 1>&4 2>&5
    exec 3<&- 4>&- 5>&-
    rm $OUTPUT_PIPE
    : "${attr}endLog end${default}"
    return $RET
}
####################################################################@END FOLD@

################################
# STEP MANAGEMENT
####################################################################@BEGIN FOLD@
# fillStepStatusFile
#-------------------
# Update the status file
fillStepStatusFile() {
    local -
    : "${attr:=$esc[0m}fillStepSatusFile $*${default:=$esc[0m}"     # to restore gvim highlight "]}]}"
    local stepsig stepstr RET=0

    [[ $startstop != start ]] && return $RET
    stepsig="STEP $step.$substep"
    case "$1" in
        substepskip)
            printf "\rSTEP %d.%-2d SKIP (%s)\n" $step $substep "$fullservice" >> $stepStatusFile
        ;;
        substepstart)
            displaymsg "$step.$substep $service $subservice"
            printf "STEP %d.%-2d  RUN (%s)..." $step $substep "$fullservice" >> $stepStatusFile
            substep=$((substep+1))
        ;;
        substep)
            printf "\rSTEP %d.%-2d %4s ( %16s: %-3d )\n" $step $substep "$ret_str" "$fullservice" $ret_script >> $stepStatusFile
            [[ "$ret_str" == "$OK" ]] && substepsuccess=$((substepsuccess+1))
        ;;
        step)
            printf "==: STEP %d succeed: %d/%d\n" $step $substepsuccess $substep >> $stepStatusFile
        ;;
    esac
    : "${attr}fillStepSatusFile end$*${default}"
    return $RET 
}

# change_step
#------------
# Process the entering of a new step
change_step() {
    local -
    : "${attr:=$esc[0m}change_step $*${default:=$esc[0m}"           # to restore gvim highlight "]}]}"
    local RET=0

    [[ $startstop != start ]] && return $RET
    if [[ $1 -ne $step ]]; then
        : "Give the previous step status"
        fillStepStatusFile step
    fi
    step=$1
    skip=$2
    substep=$substepinit
    substepsuccess=0
    echo $step > $stepFile
    fillStepStatusFile substepstart
    : "${attr}change_step end${default}"
    return $RET
}

# do_step
#--------
# Process the step
do_step() {
    local -
    : "${attr:=$esc[0m}do_step $*${default:=$esc[0m}"               # to restore gvim highlight "]}]}"
    local RET=0 _step sendsig i

    [[ $startstop != start ]] && return $RET
    # retrieve subservice, stepnumber and sendsig
    #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    _step=${subservice#*[_.]}
    if [[ "$_step" == "$subservice" ]]; then
        [[ "${_step//[![:digit:]]}" == "$_step" ]] && unset subservice || unset _step
    else
        subservice=${subservice%%[_.]*}
    fi
    _step=${_step##0} # remove leading '0'

    : "${attr}subservice=$subservice _step=$_step${default}"

    [[ -n "$_step" ]] && stepnum=$_step
    [[ "$subservice" == "sig" ]] && sendsig=1 || sendsig=0

    # process new step entering
    # (no signal sending here)
    #~~~~~~~~~~~~~~~~~~~~~~~~~~
    if [[ -n "$_step" ]]; then
        eval "BANNER=\$step${stepnum}label splash=\${step${stepnum}Splash:-}"
        attr="$esc[42;30m" default="$esc[0m" display "====    $BANNER    ===="
        # display the splash corresponding to the step
        if [[ -f "$splash" ]]; then
            if [[ ! -f $applicationManagerPid ]] || [[ ! -d /proc/$(cat $applicationManagerPid) ]]; then
                /usr/sbin/jpg2fb $splash
            fi
        fi
        # memorize the step and its skip status
        if [ -f /.skip.$stepnum -o -f /tmp/.skip.$stepnum ]; then
            change_step "$stepnum" 1
        else
            change_step "$stepnum" 0
        fi

        # process reboot at begining of step
        #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        if [[ -f /tmp/reboot.$stepnum ]]; then
            display "A reboot was requested by\n$(cat /tmp/reboot.$stepnum)"
            /sbin/reboot --waitSettings
        fi

        # step dependent actions
        case "$stepnum" in
            1) : "$BANNER"
                # activate_sm
            ;;
            4) : "$BANNER"
                deactivate_sm
                while [[ -f $lockFile ]] || [[ -f /.lockinit ]]; do
                    usleep $waittime
                done
            ;;
            5) : "$BANNER"
                # SANITY CHECK !!!!
                #~~~~~~~~~~~~~~~~~~
                # i is the number of time the test is done before rebooting
                [[ -f $sanityflag ]] && i=0 || i=5
                while [[ $i -gt 0 ]]; do
                    [[ -f $applicationManagerPid ]] && [[ -d /proc/$(cat $applicationManagerPid) ]] && break || :
                    # The application manager should always be there !!!
                    # Display 'i' times "NO APPLICATION MANAGER" and reboot
                    display "NO APPLICATION MANAGER !!!"
                    i=$((i-1))
                    [[ $i -eq 0 ]] && reboot --reason "NO APPLICATION MANAGER" --owner rcS
                    sleep 1
                done
            ;;
        esac
    fi
    # signal sending
    #~~~~~~~~~~~~~~~
    if [[ $sendsig -eq 1 ]]; then
        # send to the infra the current step
        send_infra step $stepnum 2>/dev/null
    fi

    : "${attr}do_step end${default}"
    return $RET
}
####################################################################@END FOLD@

################################
# SIGNAL HANDLER
####################################################################@BEGIN FOLD@
# rcS_exit
#---------
# Executed automatically when the script ends.
# This is done through the trap of signal 0
handler_0() {
    local -
    : "${attr:=$esc[0m}handler_0 $*${default:=$esc[0m}"             # to restore gvim highlight "]}]}"
    local RET=0

    [ -e $pidFile ] && rm $pidFile
    [ -e $commandPipe ] && rm -f $commandPipe >/dev/null 2>&1
    endLog
    RET=$?
    : "${attr}handler_0 end${default}"
    return $RET
}

# handler_commandSignal
#----------------------
# process the command pipe 
# NOTE: commandSignal is defined in "/etc/init.d/rc.config"
handler_commandSignal(){
    local -
    : "${attr:=$esc[0m}handler_commandSignal $*${default:=$esc[0m}" # to restore gvim highlight "]}]}"
    local RET=0 cmdpipe cmd arg spid sig tmp

    : "${attr}current cmdfifo: [$cmdfifo]${default}"
    read cmdpipe < $commandPipe

    # push the command into the fifo
    cmdfifo="${cmdfifo:+$cmdfifo^}$cmdpipe"

    : "${attr}current cmdfifo: [$cmdfifo]${default}"
    if [[ ${rcscmd:-0} -eq 1 ]]; then
        : "${attr}another rcS_cmd is running, getting out of here${default}"
        return 0
    fi
    rcscmd=1

    # pop a command from the fifo
    cmd=${cmdfifo%%^*} cmdfifo=${cmdfifo#$cmd} cmdfifo=${cmdfifo#^}
    # process the cmd
    while [[ -n "$cmd" ]]; do
        : "${attr}command: $cmd${default}"
        set $cmd
        # retrieve the signal number and signal to send at the end of the function if needed
        case "$1" in
            ALRM|USR1|USR2) : "${attr}Signal required at the end of the command processing${default}"
                sig=$1 spid=$2 shift 2
            ;;
            *) : "${attr}No signal required at the end of the command processing${default}"
                unset sig spid
            ;;
        esac
        # process the command from the pipe
        cmd=$1 shift
        arg=$*
        case "$(type $cmd)" in
            *"shell function") : "${attr}start shell function($cmd)${default}"
                $cmd $arg
                RET=$?
                # send the required signal to the demanding pid if needed
                [[ -n "${sig:-}" ]] && [[ -n "${spid:-}" ]] && kill -$sig $spid
            ;;
            *) : "${attr}Command not found${default}"
                echoerror "$cmd is not a command ($cmd $arg)"
                RET=-1
            ;;
        esac
        # pop a command from the fifo
        cmd=${cmdfifo%%^*} cmdfifo=${cmdfifo#$cmd} cmdfifo=${cmdfifo#^}
    done
    rcscmd=0
    : "${attr}handler_commandSignal end${default}"
    return $RET
}
####################################################################@END FOLD@

################################
# RCS COMMANDS & MANAGEMENT
####################################################################@BEGIN FOLD@

# activate_sm
#------------
# Activate the hotkey to enter the sm (setting manager).
activate_sm() {
    local -
    : "${attr:=$esc[0m}activate_sm $*${default:=$esc[0m}"           # to restore gvim highlight "]}]}"
    local RET=0

    shortkey &
    shortkeyPid=$!
    : "${attr}activate_sm end${default}"
    return $RET
}

# deactivate_sm
#--------------
# Deactivate the hotkey to access the sm (setting manager).
deactivate_sm() {
    local -
    : "${attr:=$esc[0m}deactivate_sm $*${default:=$esc[0m}"         # to restore gvim highlight "]}]}"
    local RET=0

    # kill "shortkey" if its pid is defined
    ${shortkeyPid+kill $shortkeyPid}
    unset shortkeyPid
    trap 'display "=====             SIGNAL IGNORED            ======"' USR1
    : "${attr}deactivate_sm end${default}"
    return $RET
}

# $startSMCommand
#----------------
# Start the sm (setting manager) because the hotkey was pressed.
# NOTE: startSMCommand is defined in "/etc/init.d/rc.config"
eval "
$startSMCommand() {
    local -
    local attr=\"$esc[43;30m\" default=\"$esc[0m\"
    : \"\${attr}$startSMCommand \$*\${default}\"
    local RET=0

    [[ \"\${shortkeyPid:-none}\" != \"none\" ]] && kill \${shortkeyPid}
    [[ \"\${settingsState:-none}\" == \"running\" ]] && return
    display \"=====        START SETTING MANAGER       ======\"
    : \"Ask for the start of the setting manager\"
    settingsState=running
    send_infra show_webapp Settings
    RET=\$?
    : \"\${attr}$startSMCommand end\${default}\"
    return \$RET
}
"

# noop
#-----
# Does no operation
# NOTE: this is used to debug the command processing
noop() {
    local -
    : "${attr:=$esc[0m}noop $*${default:=$esc[0m}"                  # to restore gvim highlight "]}]}"
    local RET=0
    : "${attr}noop end${default}"
    return $RET
}
####################################################################@END FOLD@

set_init() {

    ulimit -c $(awk 'BEGIN{limit=0}/^[^#].*\<core\>.*/{limit=$NF}END{print limit}' /etc/security/limits.conf /etc/security/limits.d/*)
    return 0
}

#PR261951 jerryzh+
wait_dependence_finish() {
    local script=$1 depend="" wait_pid=""
    local i

    # get script name
    #~~~~~~~~~~~~~~~~
    script=${script##*/}

    # replace the '-' to '_' in script name
    #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    script=${script//\-/\_}
    eval depend="$"$script"_DEPEND"

    for i in ${depend:-}; do
# crms00432847 zimingxu+
        wait_pid=$(cat /tmp/$i.pid 2>/dev/null)
        if [[ ! -z "$wait_pid" ]]; then
            while [[ -d /proc/$wait_pid ]]; do
                wait $wait_pid
            done
        fi
# crms00432847 zimingxu-
    done

    return 0
}

execute_script() {
    local script=$1 run_mode=$2
    local pid_file=""
	
    [[ -z $script ]] && return 1

    #create pid_file name
    #~~~~~~~~~~~~~~~~~~~~
    pid_file="/tmp/${script##*/}.pid"

    # precmd
    #~~~~~~~
    [[ -n "${precmd:-}" ]] && $precmd || : "${attrr}no precmd${default}"
	
    # execute the script
    #~~~~~~~~~~~~~~~~~~~
    timestamp=$(udate)
    echo "[$timestamp] Entering $script..."

    # we need to start the child in background and wait for its PID
    # to allow the user to start the setting manager through the shortkey
    $script $startstop <&3 &
    current_pid=$!

    # record the pid if background mode
    #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    [[ $run_mode -eq 1 ]] && echo $current_pid > $pid_file

    # wait script execute finish on background
    #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    ret_script=128
    while [ $ret_script -ge 128 -a -d /proc/$current_pid ]; do
	wait $current_pid
	ret_script=$?
    done

    # remove the pid after finish
    #~~~~~~~~~~~~~~~~~~~~~~~~~~~
    [[ $run_mode -eq 1 ]] && rm $pid_file -f

    # process the script ret code
    #~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    if [[ $ret_script -eq 0 ]]; then
	ret_str=$OK
    else
	ret_str=$NOK
    fi
    elapsetime=$(udate $timestamp)
    echo "[${elapsetime% *}] Leaving $script (${elapsetime#* }s)"
    current_pid=0
	
    # execute postcmd 
    #~~~~~~~~~~~~~~~~ 
    if [[ -n "${postcmd:-}" ]]; then
	: "exec postcmd"
	$postcmd
    else 
	: "no postcmd"
    fi

    return 0    
}

execute_post_scripts() {
    local post_script_list=$1 
    local wait_time_out=300 interval=10

    # sleep 60s before check presentation ready
    #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    sleep 60

    # check if presentation ready every 10s
    #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    while [[ ! -e $presentation_ready_flag ]] && [[ $wait_time_out -gt 0 ]]; do
        sleep $interval
        wait_time_out=`expr $wait_time_out - $interval`     
    done
   
    # sleep 30 wait homepage load ready
    #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    sleep 30

    # POST_SCRIPT_LIST is defined in '/etc/script_classification'
    #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    for i in ${post_script_list:-}; do
        (trap "" HUP; execute_script /etc/rc.d/$i 0)
    done

    return 0
}
#PR261951 jerryzh-

################################
# MAIN
####################################################################@BEGIN FOLD@
# set initial state
#~~~~~~~~~~~~~~~~~~
if [[ "X"$1 == "Xstart" ]]; then
  if [[ "$(busybox readlink /tmp)" != "/var/tmp" ]]; then
    # tmp is not a link !!!
    mv /tmp /tmp.old
    ln -s /var/tmp /tmp
    rm -rf /tmp.old &
  fi

  set_init

  #crms00407696 tingh+
  [[ -f /log/log.rcS ]] && mv /log/log.rcS /log/log.rcS.1
  defaultLogfile=/log/log.rcS
  #crms00407696 tingh-

fi

startLog
echo "[$(udate)] $0 $1..."
source $profile

# overwritting some variables from the environment configuration
warn="$esc[41;30;01m" attr="$esc[32;01m" debugattr="$esc[32;01m" default="$esc[0m"

echo $warn
[ -x /usr/sbin/debug/id ] && /usr/sbin/debug/id 
find /data/core/ -type f -exec ls -al {} \;
echo $default


# create pid file
export rcsPid=$$
echo $rcsPid > $pidFile

# set the signal handlers 
#~~~~~~~~~~~~~~~~~~~~~~~~
trap handler_0 0
deactivate_sm
trap handler_commandSignal $commandSignal

# create command pipe
#~~~~~~~~~~~~~~~~~~~~
[ -e $commandPipe ] && rm -f $commandPipe >/dev/null 2>&1
mkfifo $commandPipe

#CRMS00372430 
echo 1 > /proc/sys/kernel/printk
#CRMS00372430 end

# command line argument processing
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
startstop=$1

# In "start" mode, start all S[0-9][0-9]* scripts in /etc/init.d
# In "stop" mode, start all K[0-9][0-9]* scripts in /etc/init.d
# executing them in numerical order.
# ex. K01xx executes eariler than K10xx

# get the list of scripts to start/stop
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
case "$startstop" in
    start|"") : "${attr}start${default}"
        files=$($busybox ls $rcDir/S[0-9][0-9]*)
        postcmd="source $profile"
        startstop=start
    ;;
    stop) : "${attr}stop${default}"
        files=$($busybox ls $rcDir/K[0-9][0-9]*)
        unset postcmd
    ;;
    *) : "${attr}neither start nor stop${default}"
        echo "Usage $0 {start|stop}"
        exit 1
    ;;
esac

#PR261951 jerryzh+
# RC script run mode
#~~~~~~~~~~~~~~~~~~~
back_run=0 usecond=0
#PR261951 jerryzh-

# start/stop the retrieved list
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
for i in ${files:-}; do
    : "${attr}SCRIPT: $i${default}"
    # skip if not existing or not executable
    if [[ ! -f "$i" ]] || [[ ! -x "$i" ]]; then
        continue
    fi

#PR261951 jerryzh+
    # default execute mode is foreground
    #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    if [[ $startstop == start ]]; then
        # check applicationmanager status
        #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        if [[ $am_status -ne 1 ]] && [[ -f $applicationManagerPid ]] && [[ -d /proc/$(cat $applicationManagerPid) ]]; then
            am_status=1
        fi
        # check postpone execute script
        #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        if [[ $am_status -eq 1 ]]; then
            post=0
            for k in ${POST_SCRIPT_LIST:-}; do
                if [[ "/etc/rc.d/$k" == "$i" ]]; then
                    postattr="$esc[33m" default="$esc[0m"
                    echo "${postattr}[$(udate)] postpone $i ${default}"
                    post=1
                    break
                fi
            done
            [[ $post -eq 1 ]] && continue
        fi
        # check background execute script
        #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        back_run=0
        for k in ${BACKGROUND_SCRIPT_LIST:-}; do
            name=${k%%:[[:digit:]]*}
            if [[ "/etc/rc.d/$name" == "$i" ]]; then
                back_run=1
                if [[ "$name" == "$k" ]]; then
                    usecond=0
                else
                    usecond=${k##*:}
                fi
                break
            fi
        done

        # wait depent script finished
        #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#crms00423479 jerryzh+
        if `ls /tmp/*.pid > /dev/null 2>&1`; then
            wait_dependence_finish $i
        fi
#crms00423479 jerryzh-
    else
        # on rcS stop, to speedup reboot time, 
        # skip some unnecersary RC scripts
        #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        skip_act=0
        for k in ${SKIP_SCRIPT_LIST:-}; do
            if [[ "/etc/rc.d/$k" == "$i" ]]; then
                skipattr="$esc[33m" default="$esc[0m"
                echo "${skipattr}[$(udate)] skip $i ${default}"
                skip_act=1
                break
            fi
        done
        [[ $skip_act -eq 1 ]] && continue   
    fi
#PR261951 jerryzh-
    
    # brake script name into level/fullservice/service/subservice
    fullservice=${i##*[KS][[:digit:]][[:digit:]]}
    level=${i#*[KS]} level=${level%$fullservice}
    removeLeading "_." fullservice
    service=${fullservice##[_.]} subservice=${service#*[._]} service=${service%%[_.]*}
    if [[ "$subservice" == "$service" ]]; then
        unset subservice
    fi
    : "${attr}level=$level fullservice=$fullservice service=$service subservice=$subservice${default}"
    case "$service" in
        step*) : "Process step phase"
            do_step
            ret_script=0 ret_str=$OK
        ;;
        *) : "Process other scripts"
        #crms00423479 jerryzh+
            # check rcS pause flag
            #~~~~~~~~~~~~~~~~~~~~~
            while [[ -f $RCS_PAUSE_FLAG ]]; do
                usleep 500000
            done
        #crms00423479 jerryzh-

            # update the status file
            #~~~~~~~~~~~~~~~~~~~~~~~
            fillStepStatusFile substepstart

            # skip processing (only for start phase)
            #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            if [[ $startstop == start ]] && [ \
                 ${skip:=0} -ne 0 \
                 -o -f /.skip.$fullservice \
                 -o -f /tmp/.skip.$fullservice \
                 -o -f /.skip.S$level \
                 -o -f /tmp/.skip.S$level \
                 -o -f /.skip.S$level*$fullservice \
                 -o -f /tmp/.skip.S$level*$fullservice \
            ]; then
                echo "[$(udate)] Skipping $i"
                fillStepStatusFile substepskip
                continue
            fi

#PR261951 jerryzh+
            # execute the script
            #~~~~~~~~~~~~~~~~~~~
            if [[ $back_run -eq 1 ]]; then
                execute_script $i $back_run &
                [ $usecond -gt 0 ] && usleep $usecond
            else
                execute_script $i $back_run
            fi
#PR261951 jerryzh-
        ;;
    esac
    # update statusFile
    #~~~~~~~~~~~~~~~~~~
    fillStepStatusFile substep
done

#PR261951 jerryzh+
# execute the postpone script after presence ready
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
if [[ $startstop == start ]] && [[ $am_status -eq 1 ]]; then
    (trap "" HUP; execute_post_scripts "$POST_SCRIPT_LIST" > /dev/null) &
fi
#PR261951 jerryzh-

fillStepStatusFile step
####################################################################@END FOLD@

readCurrentConfig
updateCurrentConfig --noread
grandtime=$(udate $grandtime)
display "rcS has been executed in ${grandtime#* }s"
[[ $startstop == start ]] && displaymsg "End of system initialisation"
[[ $startstop == stop ]] && [[ -f /root/.debug.rcS ]] && lsmod && ps w

exit 0
