#!/bin/sh
#
#    Copyright (c) 1996-2017 Brocade Communications Systems, Inc.
#    All rights reserved.
#
#    Common shell functions and macros utilized by all init scripts
#

#
# Common directories
#
BINDIR=//bin
DATADIR=//share
CONFDIR=/etc
LIBDIR=//lib
LIBEXECDIR=//libexec
LOGDIR=/var
MANDIR=//man
SBINDIR=//sbin
USRDIR=//usr
USRBINDIR=//usr/bin
USRLIBDIR=//usr/lib
USRLIBEXECDIR=//usr/libexec
USRSBINDIR=//usr/sbin

CONFIGDIR=${CONFDIR}

#
# Common executables and files
#

CHECK='/sbin/chkconfig'
HOSTNAME='/bin/hostname'
KILLALL='/usr/bin/killall -q'

NULL='/dev/null'

#
# Other, compound macros
#

PATH=//sbin://bin://usr/sbin://usr/bin
export PATH

if $CHECK verbose ; then
    ECHO='echo -e'
    VERBOSE=-v
    QUIET=
else
    ECHO=:
    VERBOSE=
    QUIET=-q
fi

#
# cpid
#
# Retrieve the current control processor number, assuming a sin/hinv input
# stream.
#
cpid() {
    sed -n -e 's/^Con.\+No: \([[:digit:]]\{1,\}\).*$/\1/gp'
}

#
# chassbd
#
# Retrieve the current system platform name(Neptune or Pluto), of the form "CHASSn", where n
# is cardinal number, assuming a sin/hinv input stream.
#
chassbd() {
    sed -n -e 's/^.\+\(CHASS[[:digit:]]\{1,\}\)..*$/\1/gp'
}

#
# swbd
#
# Retrieve the current system platform name, of the form "SWBDn", where n
# is cardinal number, assuming a sin/hinv input stream.
#
swbd() {
    sed -n -e 's/^.\+\(SWBD[[:digit:]]\{1,\}\).\+$/\1/gp'
}

# RE pattern to match an IP address in dotted-decimal formation. Note,
# however, that no range checking is performed. This could match
# 999.751.330.456 as we as it could 192.168.1.1.

IPSED="\(\([[:digit:]]\{1,3\}\.\)\{3\}[[:digit:]]\{1,3\}\)"

# RE pattern to match an IP host name, which may include all upper-
# and lower-case alpha characters, decimal digits, underscores (_),
# dashes (-) and periods (.).

HOSTSED="\([[:alnum:]\._-]\+\)"

#
# sysaddr <key>
#
# Retrieve the system address appropriate for <key>, assuming an input
# stream appropriate for an Internet host name database file (e.g.
# /etc/hosts, ypcat hosts, etc.).
#
sysaddr() {
    # 1) Find the line matching on <key>. If there's a match:
    #    a) Grab the first occurrence of an IP address.
    #    b) Delete everything else.
    #    c) Print it.
    # 2) Otherwise, throw away any other line.

    sed -e "/${1}/{; \
		s/^[[:space:]]*${IPSED}[[:space:]].\+$/\1/gp; \
	    }; \
	    /^.*$/d"
}

#
# sysname <key>
#
# Retrieve the system name appropriate for <key>, assuming an input
# stream appropriate for an Internet host name database file (e.g.
# /etc/hosts, ypcat hosts, etc.).
#
sysname() {
    # 1) Find the line matching on <key>. If there's a match:
    #    a) Delete any occurences of IP addresses.
    #    b) Grab the first hostname with characters from [[:alnum:]._-].
    #    c) Delete everything else.
    #    d) Print it.
    # 2) Otherwise, throw away any other line.

    sed -e "/${1}/{; \
		s/^[[:space:]]*${IPSED}[[:space:]]*//g; \
		s/\(^${HOSTSED}\)[[:space:]].\+$/\1/gp; \
	    }; \
	    /^.*$/d"
}

# TO_VERSION_CODE >  KERNEL_VERSION(2,6,14) return 1
TO_MAJOR=2
TO_MINOR=6
TO_REVISON=34

KERNEL_MAJOR=`/bin/uname -r | /usr/bin/cut -d '.' -f 1`
KERNEL_MINOR=`/bin/uname -r | /usr/bin/cut -d '.' -f 2`
KERNEL_REVISON=`/bin/uname -r | /usr/bin/cut -d '.' -f 3 | /usr/bin/cut -c 1-2`

#
# Return 1 for platforms using new kernel version higher then 2.6.3
#
kernel_2_6_3() {

	if [ $KERNEL_MAJOR -gt $TO_MAJOR ]; then
		return 1
	fi
	if [ $KERNEL_MAJOR -eq $TO_MAJOR ] || [ $KERNEL_MINOR -eq $TO_MINOR ]; then 
		if [ $KERNEL_MINOR -gt $TO_MINOR ] || [ $KERNEL_REVISON -ge $TO_REVISON ]; then
			return 1
		fi
	fi
	
			return 0
}
##Adding changes for audit
# Log that something succeeded
success() {
  [ "$BOOTUP" != "verbose" -a -z "${LSB:-}" ] && echo_success
  return 0
}

echo_success() {
  [ "$BOOTUP" = "color" ] && $MOVE_TO_COL
  echo -n "["
  [ "$BOOTUP" = "color" ] && $SETCOLOR_SUCCESS
  echo -n $"  OK  "
  [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
  echo -n "]"
  echo -ne "\r"
  return 0
}

print_status()
{
        if [ $# = 0 ]
        then
                echo "Usage: print_status {success|failure}"
                exit 1
        fi

        case "$1" in
                success)
                        $SET_COL
                        echo -n "[  "
                        $SUCCESS
                        echo -n "OK"
                        $NORMAL
                        echo "  ]"
                        ;;
                failure)
                        $SET_COL
                        echo -n "["
                        $FAILURE
                        echo -n "FAILED"
                        $NORMAL
                        echo "]"
                        ;;
        esac

}

killproc()
{

 if [ $# = 0 ]
        then
                echo "Usage: killproc {program} [signal]"
                exit 1
        fi

        base=`basename $1`

        if [ "$2" != "" ]
        then
                killlevel=$2
        else
                nolevel=1
        fi

        pidlist=`pidof -o $$ -o $PPID -o %PPID -x $base`

        pid=""

        for apid in $pidlist
        do
                if [ -d /proc/$apid ]
                then
                        pid="$pid $apid"
                fi
        done

        if [ -n "$pid" ]
        then
                if [ "$nolevel" = 1 ]
                then
                        kill -TERM $pid
                        if ps h $pid >/dev/null 2>&1
                        then
                                kill -KILL $pid
                        fi
                        ps h $pid >/dev/null 2>&1
                        if [ $? = 0 ]
                        then
				print_status failure
                        else
                                rm -f /var/run/$base.pid
                                print_status success
                        fi
                else
                        kill $killlevel $pid
                        ps h $pid >/dev/null 2>&1
                        if [ $? = 0 ]
                        then
                                print_status failure
                        else
                                rm -f /var/run/$base.pid
                                print_status success
                        fi
                fi
        else
                print_status failure
        fi
}
# __proc_pids {program} [pidfile]
# Set $pid to pids from /var/run* for {program}.  $pid should be declared # local in the caller.
# Returns LSB exit code for the 'status' action.
__pids_var_run() {
        local base=${1##*/}
        local pid_file=${2:-/var/run/$base.pid}

        pid=
        if [ -f "$pid_file" ] ; then
                local line p

                [ ! -r "$pid_file" ] && return 4 # "user had insufficient privilege"
                while : ; do
                        read line
                        [ -z "$line" ] && break
                        for p in $line ; do
                                [ -z "${p//[0-9]/}" ] && [ -d "/proc/$p" ] && pid="$pid $p"
                        done
                done < "$pid_file"

                if [ -n "$pid" ]; then
                        return 0
                fi
                return 1 # "Program is dead and /var/run pid file exists"
        fi
        return 3 # "Program is not running"
}

# A function to start a program.
daemon() {
        # Test syntax.
        local gotbase= force= nicelevel corelimit
        local pid base= user= nice= bg= pid_file=
        local cgroup=
        nicelevel=0
        while [ "$1" != "${1##[-+]}" ]; do
          case $1 in
            '')    echo $"$0: Usage: daemon [+/-nicelevel] {program}"
                   return 1;;
            --check)
                   base=$2
                   gotbase="yes"
                   shift 2
                   ;;
            --check=?*)
                   base=${1#--check=}
                   gotbase="yes"
                   shift
                   ;;
            --user)
                   user=$2
                   shift 2
                   ;;
            --user=?*)
                   user=${1#--user=}
                   shift
                   ;;
            --pidfile)
                   pid_file=$2
                   shift 2
                   ;;
            --pidfile=?*)
                   pid_file=${1#--pidfile=}
                   shift
                   ;;
            --force)
                   force="force"
		 shift
                   ;;
            [-+][0-9]*)
                   nice="nice -n $1"
                   shift
                   ;;
            *)     echo $"$0: Usage: daemon [+/-nicelevel] {program}"
                   return 1;;
          esac
        done

        # Save basename.
        [ -z "$gotbase" ] && base=${1##*/}

        # See if it's already running. Look *only* at the pid file.
        __pids_var_run "$base" "$pid_file"

        [ -n "$pid" -a -z "$force" ] && return

        # make sure it doesn't core dump anywhere unless requested
        corelimit="ulimit -S -c ${DAEMON_COREFILE_LIMIT:-0}"

        # if they set NICELEVEL in /etc/sysconfig/foo, honor it
        [ -n "${NICELEVEL:-}" ] && nice="nice -n $NICELEVEL"

        # if they set CGROUP_DAEMON in /etc/sysconfig/foo, honor it
        if [ -n "${CGROUP_DAEMON}" ]; then
                if [ ! -x /bin/cgexec ]; then
                        echo -n "Cgroups not installed"; warning
                        echo
                else
                        cgroup="/bin/cgexec";
                        for i in $CGROUP_DAEMON; do
				 cgroup="$cgroup -g $i";
                        done
                fi
        fi

        # Echo daemon
        [ "${BOOTUP:-}" = "verbose" -a -z "${LSB:-}" ] && echo -n " $base"

        # And start it up.
        if [ -z "$user" ]; then
           $cgroup $nice /bin/bash -c "$corelimit >/dev/null 2>&1 ; $*"
        else
           $cgroup $nice runuser -s /bin/bash $user -c "$corelimit >/dev/null 2>&1 ; $*"
        fi

        [ "$?" -eq 0 ] && success $"$base startup" || failure $"$base startup"
}

# Log that something failed
failure() {
  local rc=$?
  [ "$BOOTUP" != "verbose" -a -z "${LSB:-}" ] && echo_failure
  [ -x /bin/plymouth ] && /bin/plymouth --details
  return $rc
}
echo_failure() {
  [ "$BOOTUP" = "color" ] && $MOVE_TO_COL
  echo -n "["
  [ "$BOOTUP" = "color" ] && $SETCOLOR_FAILURE
  echo -n $"FAILED"
  [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
  echo -n "]"
  echo -ne "\r"
  return 1
}
status() {
        local base pid lock_file= pid_file=

        # Test syntax.
        if [ "$#" = 0 ] ; then
                echo $"Usage: status [-p pidfile] {program}"
                return 1
        fi
        if [ "$1" = "-p" ]; then
                pid_file=$2
                shift 2
        fi
        if [ "$1" = "-l" ]; then
                lock_file=$2
                shift 2
        fi
        base=${1##*/}

        if [ "$_use_systemctl" = "1" ]; then
                systemctl status ${0##*/}.service
                return $?
        fi

        # First try "pidof"
        __pids_var_run "$1" "$pid_file"
        RC=$?
        if [ -z "$pid_file" -a -z "$pid" ]; then
                pid="$(__pids_pidof "$1")"
        fi
        if [ -n "$pid" ]; then
                echo $"${base} (pid $pid) is running..."
                return 0
        fi

        case "$RC" in
                0)
                        echo $"${base} (pid $pid) is running..."
                        return 0
                        ;;
                1)
                        echo $"${base} dead but pid file exists"
                        return 1
                        ;;
                4)
                        echo $"${base} status unknown due to insufficient privileges."
                        return 4
                        ;;
        esac
        if [ -z "${lock_file}" ]; then
                lock_file=${base}
        fi
        # See if /var/lock/subsys/${lock_file} exists
        if [ -f /var/lock/subsys/${lock_file} ]; then
                echo $"${base} dead but subsys locked"
                return 2
        fi
        echo $"${base} is stopped"
        return 3
}

