#!/usr/bin/ruby
#
# Ensure that we have a syslog-process running.
#



require 'yaml'


#
# A simple class to return an array of all running process-names and arguments
#
# This is achieved via examining the directories beneath /proc, to avoid
# having to hardcode a `ps` command which may not be portable.
#
class Processes

  # Get all running processes
  def self.running
    cmds = []

    files = Dir.glob('/proc/*/cmdline')

    files.each do |file|
      begin
        f = File.new(file, 'r')
        while (line = f.gets)
          cmds << line
          verbose("Found running process: #{line}")
        end
        f.close
      rescue StandardError
        verbose("File went away: #{file}")
      end
    end

    cmds
  end

end




if __FILE__ == $PROGRAM_NAME

  def verbose(str)
    STDERR.puts(str)
  end

  #
  # Alert(s) to raise
  #
  to_raise = []

  #
  # Did we find a syslog process?
  #
  found = false

  #
  # Get all processes and see if we have something matching
  # the pattern /syslog/ running
  #
  cmds = Processes.running

  cmds.each do |process|

    begin
      found = true if process =~ /syslog/i
    rescue ArgumentError => ex
      # If we got an invalid byte-sequence swallow it
      if ( ex.message =~ /invalid byte sequence/ )
	verbose(ex)
      else
        # Otherwise re-raise the exception.
	throw(ex)
      end
    end
  end

  if found == false
    h = {}
    h[:id]      = 'missing-syslog-low'
    h[:summary] = 'Syslog is not running.'
    h[:detail]  = '<p>We could not find a process running matching the pattern <tt>/syslog/i</tt>.</p>'

    to_raise.push(h)
  end

  # Show the output.
  puts YAML.dump(to_raise)
  exit(0)
end
