#!/usr/bin/env ruby

require 'trollop'
require 'unirest'

class CriticalStateException < StandardError; end

class CheckElasticsearch
  def self.check_node!
    st = CheckElasticsearch.new.status
    return if st == 'green'
    raise CriticalStateException, "Cluster status: #{st}"
  end

  def status
    Unirest.get("http://#{opts[:hostname]}:9200/_cluster/health").body['status']
  end

  def opts
    @opts ||= Trollop.options do
      opt :hostname,
          'Host to check',
          short: '-I',
          required: true,
          type: :string
    end
  end
end

# rubocop:disable RescueException
begin
  CheckElasticsearch.check_node!
  puts 'ELASTICSEARCH OK'
rescue CriticalStateException => e
  puts "ELASTICSEARCH CRITICAL - #{e.message}"
  exit 2
rescue Interrupt
  puts 'Interrupt'
  exit 3
rescue SystemExit => e
  raise e
rescue Exception => e
  puts "Error: #{e.message}"
  puts e.backtrace.join("\n")
  exit 3
end
# rubocop:enable RescueException
