#!/bin/bash

. /etc/rc.d/init.d/functions
. /etc/rc.d/init.d/init_functions
. /etc/profile.d/SetNNEnvVar.sh

PROCESSCONTROLLOG=/var/log/processcontrol.log

# detaillist()
# for every component process of interest, determine its status
# Note: Some components may not be monitored, ignore for now.
detaillist() {
    cd /nn/etc/scd/monitcfg
    ls -l /proc/*/exe  2>/dev/null > /tmp/startup/processcontrol_active.txt

    # check to see if there might be a configuration problem due to 
    # actions such as patch application to scd
    RELOAD_MONIT=0
    if [ -e /nn/etc/scd/monitcfg/disabled.conf ]; then
        while read processName; do
            if [ -e /nn/etc/scd/monitcfg/M?????$processName -a -e /nn/etc/scd/monitcfg/\#M?????$processName ]; then
                echo "`date`: cleaning up monitoring configuration for process $processName" >> $PROCESSCONTROLLOG
                rm -f /nn/etc/scd/monitcfg/M?????$processName
                RELOAD_MONIT=1
            fi
    
            if [ -e /etc/rc.d/rc3.d/S??$processName -a -e /etc/rc.d/rc3.d/\#S??$processName ]; then
                echo "`date`: cleaning up startup configuration for process $processName" >> $PROCESSCONTROLLOG
                rm -f /etc/rc.d/rc3.d/S??$processName
            fi
        done < /nn/etc/scd/monitcfg/disabled.conf 

        # update the monitrc file and reload monit only if required
        if [ $RELOAD_MONIT -eq 1 ]; then
            echo "`date`: update the monitrc file" >> $PROCESSCONTROLLOG
            cd /nn/etc/scd/monitcfg
            cat M* > monitrc.full
            chmod 0700 monitrc.full
            /opt/sbin/monit reload > /dev/null 2>&1
        fi
    fi

    ls -1 M???B_* M???T_* M???F_* > /tmp/startup/processcontrol_expected.txt

    # do the actual work
    while read processList; do
        processName=${processList##M????_}

        grep -w "$processName" /tmp/startup/processcontrol_active.txt > /dev/null
        if [ $? -ne 0 ]; then
            echo "$processName  Automatic       Stopped"
        else
            echo "$processName  Automatic       Running"
        fi
    done < /tmp/startup/processcontrol_expected.txt
}

# status()
# for specified component process of interest, determine its status
# Note: Some components may not be monitored, ignore for now.
status() {
    cd /nn/etc/scd/monitcfg

    if [ -e /var/run/$1.pid ] &&
       [ -d /proc/`head -1 /var/run/$1.pid` ]; then
        echo "$1  Automatic       Running"
    else
        ls -l /proc/*/exe  2>/dev/null > /tmp/startup/processcontrol_active.txt

        grep -w "$1" /tmp/startup/processcontrol_active.txt > /dev/null
        if [ $? -ne 0 ]; then
            echo "$1  Automatic       Stopped"
        else
            echo "$1  Automatic       Running"
        fi
    fi
}

start() {
        # NOTE: Time is imprecise as pidof takes long and variable period of time.
        # Assume pidof takes between 0.25s and 0.60s.
        # NOTE #2: pidof has been replaced with use of .pid files and /proc fs.

        # Desired timeout = 90s => moved to 600s on BCM 4.0
        START_TIMEOUT=1200

        /opt/sbin/monit start $1

        count=0
        result=1

        # using .ini file when specified
        suffix="pid"
        grep -w "$1" /nn/etc/scd/services.ini > /dev/null
        if [ $? -eq 0 ]; then
            suffix="ini"
        fi

        while [ "$count" -lt $START_TIMEOUT ];do
            if [ -e /var/run/$1.$suffix ] &&
               [ -d /proc/`head -1 /var/run/$1.$suffix` ]; then
                result=0
                count=$START_TIMEOUT
            else
                usleep 500000
                let "count += 1"
            fi
           # echo `date` count= $count
        done
        if [ "$2" = "q" ]; then
           return $result
        fi 

        if [ $result -eq 0 ];then 
            echo "Success";
        else
            echo "Failure";
        fi

        return $result
}

stop() {
        # NOTE: Time is imprecise as pidof takes long and variable period of time.
        # Assume pidof takes between 0.25s and 0.60s.
        # NOTE #2: pidof has been replaced with use of .pid files and /proc fs.

        # Desired timeout = 90s
        SHUTDOWN_TIMEOUT=180
        procdir=`head -1 /var/run/$1.pid`

        /opt/sbin/monit stop $1

        count=0
        result=1
        while [ $count -lt $SHUTDOWN_TIMEOUT ];do
            if [ -e /var/run/$1.pid ] &&
               [ -d /proc/$procdir ]; then
                usleep 500000
                let "count += 1"
            else
                result=0
                count=$SHUTDOWN_TIMEOUT
            fi
           # echo `date` count= $count
        done

        # Sleep for 1s to prevent start operation following too close to stop
        sleep 1

        if [ "$2" = "q" ]; then
           return $result
        fi 

        if [ $result -eq 0 ];then
            echo "Success";
        else
            echo "Failure";
        fi

        return $result
}

restart() {
        stop $1 > /dev/null
        sleep 1
        start $1 > /dev/null

        result=$?
        if [ $result -eq 0 ];then
            echo "Success";
        else
            echo "Failure";
        fi

        return $result
}

disable () {
        # The service name must be listed in /nn/etc/scd/monitcfg/monitrc.disable
        if [ ! `cat /nn/etc/scd/monitcfg/monitrc.disable | grep -w $1` ]; then
           echo "Failure"
           return 1;
        fi

        stop $1 q > /dev/null 2>&1
        pushd . > /dev/null 2>&1
        cd /nn/etc/scd/monitcfg
        if [ ! -f \#*$1 ]; then
           p_name=`ls -1 *_$1`
           mv $p_name \#$p_name
           cat M* > monitrc.full
           chmod 0700 monitrc.full
           /opt/sbin/monit reload > /dev/null 2>&1
           cd /etc/rc.d/rc3.d
           p_name=`ls -1 *[0-9]$1`
           mv $p_name \#$p_name 
           if [[ ! -e /nn/etc/scd/monitcfg/disabled.conf ]] || [[ ! `cat /nn/etc/scd/monitcfg/disabled.conf | grep -w $1 > /dev/null` ]]; then
              echo $1 >> /nn/etc/scd/monitcfg/disabled.conf
           fi
           echo "$1 Disabled"
         fi
         popd > /dev/null 2>&1

return 0  
}

enable () {
        # The service name does NOT need to be listed in /nn/etc/scd/monitcfg/monitrc.disable
        # But an entry must be present in disabled.conf
#        if [ ! -e /nn/etc/scd/monitcfg/disabled.conf -o ! `cat /nn/etc/scd/monitcfg/disabled.conf | grep -w $1` ]; then
        if [[ ! -e /nn/etc/scd/monitcfg/disabled.conf ]] || [[ ! `cat /nn/etc/scd/monitcfg/disabled.conf | grep -w $1` ]]; then
           return 1;
        fi
        pushd . > /dev/null 2>&1
        cd /nn/etc/scd/monitcfg
        dp_name=`ls -1 *_$1`
        p_name=${dp_name/##/ }
        mv $dp_name $p_name
        cat M* > monitrc.full
        chmod 0700 monitrc.full
        cd /etc/rc.d/rc3.d
        p_name=`ls -1 *[0-9]$1`
        p_name=${p_name/##/}
        mv \#$p_name $p_name
        popd > /dev/null 2>&1
        /opt/sbin/monit reload > /dev/null 2>&1
        start $1 q > /dev/null 2>&1
        echo "$1 Enabled"
        if [ -e /nn/etc/scd/monitcfg/disabled.conf ]; then 
           disabled_procs=
           while read line
             do
                if [ ! "$line" = "$1" ]; then
                   disabled_procs=`expr "$disabled_procs $line"`
                fi
           done </nn/etc/scd/monitcfg/disabled.conf
           if [ ! "$disabled_procs" = " " ]; then 
              rm -f /nn/etc/scd/monitcfg/disabled.conf
              for proc_name in $disabled_procs; do
                 echo $proc_name >> /nn/etc/scd/monitcfg/disabled.conf
              done
           else
              rm -f /nn/etc/scd/monitcfg/disabled.conf
           fi
        fi

return $result
}

updateconfig () {
    #this will look for a populated disabled.conf and disable anything found in it
    #intended for restores, startup profiles etc.
    if [ -f /nn/etc/scd/monitcfg/disabled.conf ]; then
       while read line
          do
          if [ ! -e /nn/etc/scd/monitcfg/\#*$line -o ! -e /etc/rc.d/rc3.d/\#*$line ]; then
             echo "`date` clean up the scd due to init_cleanup invocation" >> $PROCESSCONTROLLOG
             disable $line
          fi
              if [ -e /etc/rc.d/rc3.d/\#*$line -a -e /nn/etc/scd/monitcfg/\#*$line ]; then
                 echo "`date` clean up the scd due to upgrade" >> $PROCESSCONTROLLOG
                 rm -rf /nn/etc/scd/monitcfg/M?????$line
                 rm -rf /etc/rc.d/rc3.d/S??$line
                 cat /nn/etc/scd/monitcfg/M* > /nn/etc/scd/monitcfg/monitrc.full
                 chmod 0700 /nn/etc/scd/monitcfg/monitrc.full
                 /opt/sbin/monit reload > /dev/null 2>&1
          fi
       done </nn/etc/scd/monitcfg/disabled.conf
    fi
return $results
}

resetconfig () {
    #remove any disabled services, reset back to default startup 
    #for use with level 1 reset or a cleanup activity
    if [ -f /nn/etc/scd/monitcfg/disabled.conf ]; then
       while read line
          do
            enable $line
       done </nn/etc/scd/monitcfg/disabled.conf
    fi
return $results
}

case "$1" in
  detaillist)
        echo "`date` CmdLine: $0 $1" >> $PROCESSCONTROLLOG
        detaillist
        ;;
  status)
        echo "`date` CmdLine: $0 $1" >> $PROCESSCONTROLLOG
        status $2
        ;;
  start)
        echo "`date` CmdLine: $0 $1 $2" >> $PROCESSCONTROLLOG
        start $2
        ;;
  stop)
        echo "`date` CmdLine: $0 $1 $2" >> $PROCESSCONTROLLOG
        stop $2
        ;;
  restart)
        echo "`date` CmdLine: $0 $1 $2" >> $PROCESSCONTROLLOG
        restart $2
        ;;
  disable)
        echo "`date` CmdLine: $0 $1 $2" >> $PROCESSCONTROLLOG
        disable $2
        ;;
  enable)
        echo "`date` CmdLine: $0 $1 $2" >> $PROCESSCONTROLLOG
        enable $2
        ;;
  updateconfig)
        echo "`date` CmdLine: $*" >> $PROCESSCONTROLLOG
        updateconfig
        ;;
  resetconfig)
        echo "`date` CmdLine: $*" >> $PROCESSCONTROLLOG
        resetconfig
        ;;
  *)
        echo "`date` CmdLine: $0 $1 $2" >> $PROCESSCONTROLLOG
        echo $"Usage: $0 {detaillist|start <component>|stop <component>|restart <component>|disable <component>|enable <component>|updateconfig|resetconfig}"
        exit 1
esac

exit $?
