#!/bin/sh

DEBUG=1
# Can't log to /mnt/log since we will be unmounting that filesystem
#LOGFILE=/mnt/log/os/preprestart.log
LOGFILE=/mnt/ramdisk/preprestart.log

debug_print ()
{
    if [ $DEBUG -ne 0 ]; then
        echo $1
        echo "$(date +%T.%N) :: $1" >> $LOGFILE
        logger "$1"
    fi
}

#
# Kill the passed in process
# $1 = PID
# $2 = Timeout in seconds
#
kill_process()
{
    if [[ -z "$1" ]] || [[ -z "$2" ]]
    then
        # Bad parameters, do nothing
        :
    else
        local pid=$1
        local timeout=$2

        debug_print "Killing $pid: '$(cut -d "" -f 1 /proc/$pid/cmdline | head -1)'"

        local startTime=$(date +%s)
        local didTimeout=0
        # Ask the process to die
        kill -9 $pid >> $LOGFILE 2>&1
        while [[ $(kill -0 $pid 2> /dev/null) ]]
        do
            # Make sure we eventually timeout while waiting
            if [[ $(( $(date +%s) - $startTime )) -gt $timeout ]]
            then
                debug_print "Timed out killing $pid"
                $didTimeout=1
                break
            fi
        done

        # If we timed out waiting...
        if [ $didTimeout -eq 0 ]
        then
            debug_print "$pid terminated"
        else
            # We already sent 'kill -9', so we don't have a more forceful kill to try.
            # Just print the error and return.
            debug_print "Timed out waiting for $currPID to terminate."
        fi
    fi
}

kill_process $(pidof mccli) 5
kill_process $(pidof logc) 5
kill_process $(pidof appsv) 5
kill_process $(pidof web) 5
kill_process $(pidof rpcd) 5
kill_process $(pidof rpcget) 5
kill_process $(pidof pfud) 5
kill_process $(pidof udhcpc) 5
kill_process $(pidof ntpclient) 5
kill_process $(pidof crond) 5
kill_process $(pidof outertrack) 5

# Additions for Gallium
# TODO: watchdog?
kill_process $(pidof sfcbd) 5
kill_process $(pidof snmpd) 5

# NOTE: The following file is auto-generated by app_AppManager.cpp::AppManager::AppManager()
if [ -f /usr/bin/killappslogc ]
then
    /usr/bin/killappslogc >> $LOGFILE 2>&1
fi

# NOTE: The following file is auto-generated by app_AppManager.cpp::AppManager::AppManager()
if [ -f /usr/bin/killappsappsv ]
then
    /usr/bin/killappsappsv >> $LOGFILE 2>&1
fi

