#!/bin/sh
#
# newrelic-sysmond <summary>
#
# chkconfig:   2345 80 20
# description: Starts and stops the New Relic Server Monitor Daemon.
# processname: nrsysmond
# config:      /etc/newrelic/nrsysmond.cfg

LANG=C
NAME=newrelic-sysmond
PROG=nrsysmond
DESC="Server Monitor"

# Source function library.
. /etc/init.d/functions

id=`id -u 2> /dev/null`
if [ "$id" != "0" ]; then
  if [ -z "${NR_SILENT}" -a -z "${SILENT}" ]; then
    echo "ERROR: must run $0 as root"
  fi
  exit 1
fi

# Source defaults
if [ -f /etc/sysconfig/${NAME} ]; then
  . /etc/sysconfig/${NAME}
fi

if [ -z "${nrdaemon}" ]; then
  if [ -x /usr/sbin/${PROG} ]; then
    nrdaemon=/usr/sbin/${PROG}
  elif [ -x /usr/local/sbin/${PROG} ]; then
    nrdaemon=/usr/local/sbin/${PROG}
  fi
fi

if [ -z "${nrdaemon}" ]; then
  if [ -z "${NR_SILENT}" -a -z "${SILENT}" ]; then
    echo "ERROR: ${PROG} not found"
  fi
  exit 6
fi

if [ ! -x "${nrdaemon}" ]; then
  if [ -z "${NR_SILENT}" -a -z "${SILENT}" ]; then
    echo "ERROR: ${nrdaemon} not executable"
  fi
  exit 6
fi

if [ -z "${cfgfile}" ]; then
  if [ -f /etc/newrelic/${PROG}.cfg ]; then
    cfgfile=/etc/newrelic/${PROG}.cfg
  elif [ -f /etc/${PROG}.cfg ]; then
    cfgfile=/etc/${PROG}.cfg
  elif [ -f /usr/local/etc/${PROG}.cfg ]; then
    cfgfile=/usr/local/etc/${PROG}.cfg
  fi

  if [ -z "${cfgfile}" ]; then
    cfgfile=`echo "${nrdaemon}" | sed -e "s/${PROG}/${PROG}.cfg/" 2> /dev/null`
  fi
fi

if [ ! -f "${cfgfile}" ]; then
  if [ -z "${NR_SILENT}" -a -z "${SILENT}" ]; then
    echo "ERROR: ${PROG}.cfg not found"
  fi
  exit 5
fi

#
# Read the pidfile setting from the configuration file
#
pidfile=`sed -n -e 's/^[ 	]*pidfile[ 	]*=[ 	]*//p' -e 's/[ 	]*$//' "${cfgfile}" 2> /dev/null`

#
# If the configuration file didn't have a pidfile setting, then we
# must assume a default value instead
#
pidarg=
if [ -z "${pidfile}" ]; then
  if [ -d /var/run ]; then
    pidfile=/var/run/newrelic/${PROG}.pid
  elif [ -d /var/pid ]; then
    pidfile=/var/pid/${PROG}.pid
  else
    pidfile=/etc/${PROG}.pid
  fi
  pidarg=" -p ${pidfile}"
fi

nrdaemonopts="-c ${cfgfile}${pidarg}"

#
# It's just cosmetic but lets figure how to suppress newlines in echo
#
if echo ' \c' | grep 'c' > /dev/null 2>&1; then
  en='-n'
  ec=''
else
  en=''
  ec='\c'
fi

lockfile=/var/lock/subsys/${NAME}

#
# Time to wait for the daemon to die, in seconds. If you set this too low the
# daemon may not have enough time to flush pending data with the New Relic
# servers, and the restart command may not work.
#
DODTIME=15

# Check if a given process pid's cmdline matches a given name
running_pid()
{
  pid=$1
  name=$2
  [ -z "$pid" ] && return 1
  [ ! -d /proc/$pid ] && return 1
  cmd=`cat /proc/$pid/cmdline | tr "\000" "\n"|head -n 1 |cut -d : -f 1`
  # Is this the expected child?
  [ "$cmd" = "$name" ] || return 1
  return 0
}

# Check if the process is running looking at /proc
running()
{
  # if there are _any_ processes like '/nrsysmond ' running then assume
  # the server monitor is running.  This check was needed to allow for
  # correct detection of running nrsysmonds even though they may have
  # (as observed in 1.2.0.257) failed to write their pidfile.
  nrsysmond_count=`ps -ef | grep '/nrsysmond ' | grep -v grep | wc -l`
  if [ "x${nrsysmond_count}" != "x0" ]; then
    return 0
  fi

  # The rest of this function is, at this point, probably vestigal ...
  # but we will leave it in place for now while the above logic is 
  # prooved out.

  # No pidfile, probably no daemon present
  [ -f "${pidfile}" ] || return 1
  # Obtain the pid and check it against the binary name
  pid=`cat ${pidfile}`
  running_pid "${pid}" "${nrdaemon}" || return 1
  return 0
}

start() {
  HAVE_LICENSE_KEY="yes"
  if sed -e '/^[ 	]*#/d' "${cfgfile}" 2> /dev/null | grep -q 'REPLACE_WITH_REAL_KEY' 2> /dev/null; then
    if [ ! -z "$NEW_RELIC_LICENSE_KEY" ]; then
      sed -i.bak -e "s/^\(license_key=\).*/\\1${NEW_RELIC_LICENSE_KEY}/" "${cfgfile}" 2>/dev/null
      if [ ! $? ]; then
        HAVE_LICENSE_KEY="no"
      fi
    else
      HAVE_LICENSE_KEY="no"
    fi
  fi

  if [ "x$HAVE_LICENSE_KEY" = "xno" ]; then
    if [ -z "${NR_SILENT}" -a -z "${SILENT}" ]; then
      cat <<EOF

*********************************************************************
*********************************************************************
***
***  Can not start the New Relic Server Monitor until you insert a
***  valid license key in the following file:
***
***     ${cfgfile}
***
***  You can do this by running the following command as root:
***
***     nrsysmond-config --set license_key=<your_license_key_here>
***
***  No data will be reported until the server monitor can start.
***  You can get your New Relic key from the 'Configuration' section
***  of the 'Support' menu of your New Relic account (accessible at
***  https://rpm.newrelic.com).
***
*********************************************************************
*********************************************************************

EOF
    fi
    return 1
  fi

  if running ; then
    if [ -z "${NR_SILENT}" -a -z "${SILENT}" ]; then
      echo "$NAME already running"
    fi
    return 0
  fi

  if [ -z "${NR_SILENT}" -a -z "${SILENT}" ]; then
    echo ${en} "Starting $NAME: ${ec}"
  fi

  # ensure that the pidfile path exists
  pidfilepath=`dirname ${pidfile}`
  if [ ! -d "${pidfilepath}" ]; then
    mkdir -p "${pidfilepath}"
    chmod 755 "${pidfilepath}"
    if [ -n "${RUNAS}" -a "${RUNAS}" != "root" ]; then
      chown "${RUNAS}":"${RUNAS}" "${pidfilepath}"
    fi
  fi


  RETVAL=0
  if [ -z "${RUNAS}" -o "${RUNAS}" = "root" ]; then
    "${nrdaemon}" ${nrdaemonopts} || RETVAL=1
  else
    cfgpath=`dirname ${cfgfile}`
    chmod og+x ${cfgpath}
    touch "${pidfile}" 
    chown "${RUNAS}":"${RUNAS}" "${pidfile}"
    chmod 644 "${pidfile}"
    su ${RUNAS} -s /bin/sh -c "env -i ${nrdaemon} ${nrdaemonopts}" || RETVAL=1
  fi

  sleep 1
  if [ "x${RETVAL}" = "x0" ]; then
    if running ; then
      RETVAL=0
    else
      RETVAL=1
    fi
  fi

  if running ; then
    touch $lockfile
    if [ -z "${NR_SILENT}" -a -z "${SILENT}" ]; then
      success
      echo
    fi
    return 0
  else
    if [ -z "${NR_SILENT}" -a -z "${SILENT}" ]; then
      failure
      echo
    fi
    return 1
  fi
}

stop() {
  if [ -z "${NR_SILENT}" -a -z "${SILENT}" ]; then
    echo ${en} "Stopping $NAME: ${ec}"
  fi

  if running ; then
    killproc -p $pidfile $PROG
    tleft=0
    while test $tleft -lt $DODTIME; do
      if running ; then
        sleep 1
        tleft=$(($tleft+1))
      else
        rm -f $lockfile > /dev/null 2>&1
        if [ -z "${NR_SILENT}" -a -z "${SILENT}" ]; then
          success
          echo
        fi
        return 0
      fi
    done
  else
    rm -f $lockfile > /dev/null 2>&1
    if [ -z "${NR_SILENT}" -a -z "${SILENT}" ]; then
      success
      echo
    fi
    return 0
  fi

  if running ; then
    killproc -9 -p $pidfile $PROG
    tleft=0
    while test $tleft -lt 5; do
      if running; then
        sleep 1
        tleft=$(($tleft+1))
      else
        rm -f $lockfile > /dev/null 2>&1
        if [ -z "${NR_SILENT}" -a -z "${SILENT}" ]; then
          success
          echo
        fi
        return 0
      fi
    done
  fi

  # send SIGTERM to all processes on the system like '/nrsysmond '
  if running ; then
    for p in `ps -ef | grep '/nrsysmond ' | grep -v grep | awk '{print $2;}'`; do kill -15 $p > /dev/null 2>&1; done
  fi

  # we tried to be nice, now we mean it ... send SIGKILL to all processes
  # on the system like '/nrsysmond ' 
  if running ; then
    for p in `ps -ef | grep '/nrsysmond ' | grep -v grep | awk '{print $2;}'`; do kill -9 $p > /dev/null 2>&1; done
  fi

  if running ; then
    if [ -z "${NR_SILENT}" -a -z "${SILENT}" ]; then
      failure
      echo
    fi
  else
    rm -f $lockfile > /dev/null 2>&1
    if [ -z "${NR_SILENT}" -a -z "${SILENT}" ]; then
      success
      echo
    fi
    return 0
  fi

  return 1
}

restart() {
  stop || return 1
  sleep 1
  start || return 1
  return 0
}

reload() {
  restart
}

force_reload() {
  restart
}

rh_status() {
  if running ; then
    if [ -z "${NR_SILENT}" -a -z "${SILENT}" ]; then
      echo "$NAME is running..."
    fi
    return 0
  else
    if [ -z "${NR_SILENT}" -a -z "${SILENT}" ]; then
      echo "$NAME is stopped..."
    fi
    return 3
  fi
}

rh_status_q() {
  rh_status >/dev/null 2>&1
}


case "$1" in
  start)
    rh_status_q && exit 0
    start
    RETVAL=$?
    ;;
  stop)
    rh_status_q || exit 0
    stop
    RETVAL=$?
    ;;
  restart)
    restart
    RETVAL=$?
    ;;
  reload)
    rh_status_q || exit 7
    reload
    RETVAL=$?
    ;;
  force-reload)
    force_reload
    RETVAL=$?
    ;;
  status)
    rh_status
    RETVAL=$?
    ;;
  condrestart|try-restart)
    rh_status_q || exit 0
    restart
    RETVAL=$?
    ;;
  *)
    if [ -z "${NR_SILENT}" -a -z "${SILENT}" ]; then
      echo "Usage: $0 {start|stop|status|restart|condrestart|try-restart|reload|force-reload}" >&2
    fi
    exit 2
    ;;
esac
exit $RETVAL

