#!/opt/sensu/embedded/bin/ruby
require 'sensu-handler'
require 'net/https'
require 'uri'
require 'json'
require 'timeout'

class OpsgenieHeartbeat < Sensu::Handler

  def handle
    Timeout.timeout(10) do
      opsgenie_heartbeat
    end
  rescue Timeout::Error
    puts 'heartbeat timed out'
  rescue => error
    puts "Error sending heartbeat: #{error.message}", error.backtrace
  end

  def opsgenie_heartbeat
    params = {}
    params['apiKey'] = '70bb80c1-11ca-44cf-ac96-e72b79254071'
    params['name'] = 'CPE-Tools-Sensu'

    uri = URI.parse('https://api.opsgenie.com/v1/json/heartbeat/send')
    http = Net::HTTP.new(uri.host, uri.port)
    http.use_ssl = true
    http.verify_mode = OpenSSL::SSL::VERIFY_NONE
    request = Net::HTTP::Post.new(uri.request_uri, 'Content-Type' => 'application/json')
    request.body = params.to_json
    http.request(request)
  end

end

