#! /usr/bin/ruby

#
# A script to check Amazon Webservice's Health Status Dashboard
#
# Jens Braeuer, github.com/jbraeuer
#
# Version 1.0
#
require 'rubygems'
require 'nokogiri'
require 'open-uri'
require 'pp'

module Nagios
  EXIT_OK = 0
  EXIT_CRIT = 1
  EXIT_UNKNOWN = 3

  module AWS
    class DashboardService
      def initialize(opts, tr)
        @tr = tr
        @opts = opts
      end

      def ok?
        @tr[2].text == "Service is operating normally."
      end

      def name
        @tr[1].text
      end

      def beautify
        @opts[:removes].inject(name()) { |input, rm| input.gsub(rm, "") }.lstrip.strip
      end
    end

    class DashboardCheck
      def initialize(opts)
        @opts = opts
        @url = "http://status.aws.amazon.com/"
      end

      def run
        states = scrape

        if states[:troubles].empty?
          puts "OK: #{states[:ok].map { |i| i.beautify }.join(', ')}"
          return EXIT_OK
        else
          puts "CRIT: #{states[:troubles].map { |i| i.beautify }.join(', ')}"
          return EXIT_CRIT
        end
      end

      :private
      def scrape
        doc = Nokogiri::HTML(open(@url))

        states = {:troubles => [], :ok => [] }
        doc.xpath("//div[@id = '#{@opts[:region]}']//tbody/tr").each do |item|

          service = Nagios::AWS::DashboardService.new @opts, item.xpath("./td")
          if enabled?(service)
            states[:ok] << service if service.ok?
            states[:troubles] << service unless service.ok?
          end
        end
        return states
      end

      def enabled?(service)
        enabled = @opts[:services].select { |filter| service.name.include? filter }
        return enabled.length > 0
      end
    end
  end
end

begin
  opts = {
    :removes => [ "Amazon", "AWS", "(Ireland)" ],
    :services => [ "Elastic Compute Cloud", "Simple Storage Service" ],
    :region => "EU_block",
  }

  check = Nagios::AWS::DashboardCheck.new(opts)
  exit check.run()
rescue => e
  warn e.message
  warn e.backtrace.join("\n")
  exit Nagios::EXIT_UNKNOWN
end
