# frozen_string_literal: true

require 'eventmachine'
require 'em-http-request'
require 'sensu/extension/tueor'

module Sensu::Extension
  class LoadCheck < TueorCheck

    def name
      'loadcheck'
    end

    def description
      'Check the load averages on a linux machine'
    end

    def definition
      {
          :type => "check",
          :name => name,
      }
    end

    prep_step(:get_cores, :cores) do
      path = File.join('/proc', 'cpuinfo')
      command(:grep).arg(:c).params('processor', path) do |output|
        set :cores, output.to_i
        set :critical_threshold, [cores * 15, cores * 10, cores * 7.5]
        set :warning_threshold, [cores * 3, cores * 2, cores * 1.5]
      end
    end

    step(:get_averages, :averages, :message) do
      path = File.join('/proc', 'loadavg')
      read_file(path) do |output|
        set :averages, output.split.take(3).collect(&:to_f)
        set :message, averages.join('  ')
      end
    end

    def critical?
      averages.zip(critical_threshold).any? { |avg, threshold| avg > threshold }
    end

    def warning?
      averages.zip(warning_threshold).any? { |avg, threshold| avg > threshold }
    end

  end
end
