#!/opt/sensu/embedded/bin/ruby
require 'sensu-handler'
require 'securerandom'
require 'aws-sdk-kinesis'
require 'json'

class CharonRelay < Sensu::Handler

  def handle
    @kinesis = Aws::Kinesis::Client.new(region: 'us-west-2', credentials: CachingCredentialsECS.new)
    @kinesis.put_records({
                             stream_name: 'charon-prod-pdx',
                             records: [
                                 {
                                     data: @event.to_json,
                                     partition_key: SecureRandom.uuid
                                 }
                             ]
                         })
  rescue => error
    puts "Error adding event to kinesis: #{error.message}", error.backtrace
  end

end

class CachingCredentialsECS < Aws::ECSCredentials

  private 

  def cache_file 
    @cache_file ||= '.credential_cache'
  end

  def get_credentials
    creds = cached_credentials 
    return creds unless creds.nil?

    # We need to refresh
    File.open("#{cache_file}.lock", 'w') do |f|
      f.flock(File::LOCK_EX)
      creds = cached_credentials 
      return creds unless creds.nil?

      creds = super
      File.open(cache_file, 'w') {|f| f.puts creds } 
      creds
    end
  end

  def cached_credentials
    return nil unless File.exist?(cache_file)

    creds = JSON.parse(File.read(cache_file))
    return nil unless creds['Expiration']

    return nil if (Time.now.to_i + 5 * 60) > Time.iso8601(creds['Expiration']).to_i

    creds.to_json
  rescue Exception
    nil
  end

end
