#!/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 messages in the postfix mailq.
#
class PostfixMailQ
  #
  #  Count via "postqueue" + grep.
  #
  def self.count
    if File.executable?('/usr/sbin/postqueue') || ENV['TEST']
      c = Bytemark::Healthcheck::CommandWrapper.run_command('/usr/sbin/postqueue -p | grep -c ^[A-Z0-9]')
      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 = PostfixMailQ.count
  verbose("mailq has #{count} entries")

  #
  #  Determine how many is too high.
  #
  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] = 'postfix-mailq'
    h[:summary] = 'Too many messages in the postfix mailq'
    h[:detail] = "<p>There are #{count} messages in the postfix 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
