#! /usr/bin/env ruby
# frozen_string_literal: true

require 'sensu/extension/tueor'

module Sensu::Extension
  class MemoryCheck < TueorCheck

    def name
      'linux-memory-check'
    end

    def description
      'Check the memory usage on a linux machine'
    end

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

    prep_step(:set_default_thresholds) do
      set :critical_threshold, 90
      set :warning_threshold, 85
    end

    step(:get_memory_usage, :used_percentage, :message) do
      path = File.join('/proc', 'meminfo')
      read_file(path) do |output|

        stats = Hash.new

        output.split("\n").each do |line|
           stat, value, _ = line.split(/[:\s]+/)
           stats[stat.snakecase] = value.to_f
        end

        mem_free_kb = stats['mem_free'] + stats['buffers'] + stats['cached']

        set :used_percentage, (1 - mem_free_kb / stats['mem_total']) * 100
        set :message, "SECRET: #{test_secret} --- #{used_percentage.round(2)}%  #{stats['mem_total'] - mem_free_kb}KB Used"

      end
    end

    def critical?
      used_percentage >= critical_threshold
    end

    def warning?
      used_percentage >= warning_threshold
    end

  end
end
