#!/usr/bin/ruby

require 'yaml'

#
# Allow access to our common-code.
#
$LOAD_PATH << '/usr/share/bytemark'
$LOAD_PATH << '../lib/bytemark' if ENV['TEST'] && ENV['TEST_PREFIX']

require 'healthcheck/command_output'

#
# Count the pending messages in the exim4 mailq and alert if there are
# too many. By default '500' is the threshold, but this can be changed.
#
class EximMailQ
  #
  #  Invoke exim4 to see how many messages are in the queue.
  #
  def self.count
    if File.executable?('/usr/sbin/exim4') || ENV['TEST']
      c = Bytemark::Healthcheck::CommandWrapper.run_command('/usr/sbin/exim4 -bpc')
      return c.to_i unless c.nil?
    end
    0
  end
end

if __FILE__ == $PROGRAM_NAME

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

  to_raise = []

  #
  #  Count pending messages.
  #
  count = EximMailQ.count
  verbose("exim4 mailq has #{count} entries")

  #
  #  Determine how many is too many.
  #
  max = 500
  if File.exist?('/etc/mailq.threshold')
    new_max = File.readlines('/etc/mailq.threshold').first
    max = new_max.chomp.to_i unless new_max.nil?
  end

  #
  #  If the count is too high alert.
  #
  if count >= max
    h = {}
    h[:id] = 'exim4-mailq'
    h[:summary] = 'Too many messages in the exim4 mailq'
    h[:detail] = "<p>There are #{count} messages in the exim4 mailq.  That might mean the host is compromised, or otherwise broken.  If the threshold of #{max} is too low please edit '/etc/mailq.threshold'.</p>"
    to_raise.push(h)
  end

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