#!/usr/local/bin/perl

# nodewatch_up
#
# Version 1.2
#
# Patrick Ryan <pryan@fhcrc.org>
#
# July 22, 1997
#
# This program tries to make sure that a program is running.  If it isn't
# then it starts it.  If at least one is running, then it does nothing.

##################################################################
# Start configurable section.
##################################################################

# Set the process status command and a filter.
$ps = '/usr/bin/ps -A -o args | /usr/bin/grep';

# The command to execute.
$cmd = "/usr/local/sbin/nodewatch";

# Set the name of the process.
$name = "/usr/local/bin/perl /usr/local/sbin/nodewatch";

# Syslog configuration.

  # Should the process ID be displayed in the syslog?
  $syslog_show_pid = 0;

  # What should the process be called when making entries to the syslog?
  $syslog_p_name = "nodewatch_up";

  # What classification should the process be given?
  $syslog_p_type = "daemon";

  # What classification should messages (except error) be given?
  $syslog_m_type = "notice";

##################################################################
# End configurable section.
##################################################################

# Get processes that have the $name string in them.
@result = `$ps \'$name\'`;

# Set the number of processes found to zero.
$num = 0;

# Figure out if $name is running.
foreach $process (@result) {
  $num++ if ($process =~ /^$name$/);
}

# Now, let's start processes that aren't running...
# First, this process forks and then, in the child process, substitutes
# this process for the one that is being started up.

if (!$num) {
  if (fork() == 0) {
    to_syslog("Starting $name...");
    exec($cmd);
  }
}

sub to_syslog {
  # Sends messages to syslog.  Takes one argument: the message.
  # Depends on $syslog_show_pid, $syslog_p_name, $syslog_p_type,
  # $syslog_m_type, &openlog, &syslog, and &closelog (those three
  # from the Sys::Syslog namespace).

  my($msg) = $_[0];

  use Sys::Syslog;

  # Display the process id in the syslog message if it is set to do so.
  if ($syslog_show_pid) {
    openlog($syslog_p_name, 'pid', $syslog_p_type);
  } else {
    openlog($syslog_p_name, '', $syslog_p_type);
  }

  syslog($syslog_m_type, $msg);

  closelog();
}

