#!/usr/bin/ruby -rubygems
#
# Usage information at the end of the script.
#

require 'getoptlong'
require 'custodian/settings'
require 'custodian/queue'

#
#  Entry-point to our code.
#
if __FILE__ == $PROGRAM_NAME

  flush   = false
  stats   = false
  help    = false
  manual  = false
  monitor = nil

  begin
    opts = GetoptLong.new(
      ['--flush',   '-f', GetoptLong::NO_ARGUMENT],
      ['--help',    '-h', GetoptLong::NO_ARGUMENT],
      ['--manual',  '-m', GetoptLong::NO_ARGUMENT],
      ['--monitor', '-M', GetoptLong::OPTIONAL_ARGUMENT],
      ['--stats',   '-s', GetoptLong::NO_ARGUMENT]
                          )
    opts.each do |opt, arg|
      case opt
      when '--monitor' then
        if  arg
          monitor = arg.to_i
        else
          monitor = 5000
        end
      when '--stats' then
        stats = true
      when '--flush' then
        flush = true
      when '--help' then
        help = true
      when '--manual' then
        manual = true
      end
    end
  rescue StandardError => ex
    puts "Option parsing failed: #{ex}"
    exit
  end

  #
  # Show the help information.
  #
  if manual || help
    DATA.read.split("\n").each do |line|
      puts Regexp.last_match(1).dup if line =~ /^# ?(.*)/
    end
    exit 0
  end

  #
  #  Create the queue object.
  #
  queue = Custodian::RedisQueueType.new()

  #
  # Alerting on a queue that is too-full?
  #
  unless monitor.nil?

    #
    # Find the number of jobs
    #
    jobs = queue.size?

    if jobs > monitor
      exit 1
    else
      exit 0
    end
  end

  #
  # Showing stats?
  #
  if stats
    jobs = queue.size?
    puts "There are #{jobs || 0} jobs pending."
    exit(0)
  end

  #
  #  Are we flushing the queue?
  #
  queue.flush! if flush

end


__END__
# NAME
#  custodian-queue - Work with the queue.
#
# SYNOPSIS
#  custodian-queue  [ -h | --help ]
#                   [ -m | --manual ]
#                   [ -M | --monitor ]
#                   [ -f | --flush ]
#                   [ -s | --stats ]
#
# OPTIONS
#
#  -h, --help          Show a help message, and exit.
#
#  -m, --manual        Show this manual, and exit.
#
#  -M, --monitor       If the queue size exceeds the given threshold
#                      then report that via an exit code.
#
#  -f, --flush         Flush the queue, removing all jobs.
#
#  -s, --stats         Show the count of pending jobs.
#
#
# ABOUT
#
# This tool is designed to inspect the global queue, and also allows that
# queue to be flushed of all pending-jobs.
#
# AUTHOR
#
#  Steve Kemp  <steve@bytemark.co.uk>
#