#! /bin/sh
#
### BEGIN INIT INFO
# Provides:          newrelic-sysmond
# Required-Start:    $network $local_fs $remote_fs
# Required-Stop:     $remote_fs
# Should-Start:      $named
# Should-Stop:
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: The New Relic Server Monitor
# Description:       The New Relic Server Monitoring agent
### END INIT INFO

LANG=
PATH=/sbin:/usr/sbin:/bin:/usr/bin:/usr/local/sbin:/usr/local/bin
LABEL=newrelic-sysmond
NAME=newrelic-sysmond
PROG=nrsysmond
DESC="New Relic Server Monitor"

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 4
fi

if [ -f /lib/lsb/init-function ]; then
  . /lib/lsb/init-functions
else
log_begin_msg() {
  echo -n "$@"
}

log_end_msg() {
  if [ $1 -eq 0 ]; then
    echo " OK"
  else
    echo " FAILED"
  fi
}

fi

# Source the defaults
if [ -f /etc/default/${NAME} ]; then
  . /etc/default/${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}"

#
# 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
}

# Forcefully kill the process. Attempt to do a clean shutdown using the daemon
# command but fall back to using signals if we must.
force_stop() {
  pid=
  if [ -f "${pidfile}" ]; then
    pid=`cat ${pidfile}`
  fi

  if [ ! -z "${pid}" ]; then
    if running ; then
      kill -15 ${pid} > /dev/null 2>&1
      tleft=0
      while test $tleft -lt $DODTIME; do
        if running ; then
          sleep 1
          tleft=$(($tleft+1))
        else
          return 0
        fi
      done
    else
      return 0
    fi

    if running ; then
      kill -9 ${pid} > /dev/null 2>&1
      tleft=0
      while test $tleft -lt 5; do
        if running; then
          sleep 1
          tleft=$(($tleft+1))
        else
          return 0
        fi
      done
    fi
  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
    return 1
  fi

  return 0
}

start() {
  if running ; then
    if [ -z "${NR_SILENT}" -a -z "${SILENT}" ]; then
      echo "$DESC: $NAME already running"
    fi
    exit 0
  fi


  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
      #
      # WARNING - This text is duplicated in newrelic-sysmond.postinst
      #
      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
    exit 1
  fi

  if [ -z "${NR_SILENT}" -a -z "${SILENT}" ]; then
    log_begin_msg "Starting $DESC: $NAME"
  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 [ -z "${NR_SILENT}" -a -z "${SILENT}" ]; then
    log_end_msg $RETVAL
  fi
  return $RETVAL
}

stop() {
  if running; then
    if [ -z "${NR_SILENT}" -a -z "${SILENT}" ]; then
      log_begin_msg "Stopping $DESC: $NAME"
    fi
    force_stop
    RETVAL=$?
    if [ -z "${NR_SILENT}" -a -z "${SILENT}" ]; then
      log_end_msg $RETVAL
    fi
    return $RETVAL
  fi
  return 0
}

status() {
  if running ; then
    isnot="is"
    RETVAL=0
  else
    isnot="is not"
    if [ -f "$pidfile" ]; then
      RETVAL=1
    else
      RETVAL=3
    fi
  fi

  if [ -z "${NR_SILENT}" -a -z "${SILENT}" ]; then
    echo "$DESC: $NAME ${isnot} running"
  fi
  exit $RETVAL
}

case "$1" in
  start)
    start || exit 1
    ;;
  stop | force-stop)
    stop || exit 1
    ;;
  force-reload | restart)
    stop || exit 1
    sleep 1
    start || exit 1
    ;;
  status)
    status
    ;;
  *)
    if [ -z "${NR_SILENT}" -a -z "${SILENT}" ]; then
      echo "Usage: $0 {start|stop|restart|force-reload|status|force-stop}" >&2
    fi
    exit 2
    ;;
esac

exit 0
