#!/usr/bin/env ruby

#%# family=auto
#%# capabilities=autoconf

begin
  require 'json'
rescue LoadError
  require 'rubygems'
  require 'json'
end

label = ENV["label"]
@groonga = ENV["groonga"] || "groonga"
@host = ENV["host"] || "localhost"
@port = ENV["port"] || 10041
@protocol = ENV["protocol"] || "gqtp"

command = ARGV.shift

def parse(success, result)
  if success
    begin
      status, body = JSON.parse(result)
      return_code, start_time, elapsed, error_message = status
      if return_code.zero?
        [success, body]
      else
        [false, error_message]
      end
    rescue JSON::ParserError
      [false, $!.message]
    end
  else
    [success, result]
  end
end

def run(command, *args)
  if @protocol == "http"
    require "net/http"
    begin
      response = Net::HTTP.start(@host, @port) do |http|
        http.get("/d/status.json")
      end
      if response.is_a?(Net::HTTPSuccess)
        parse(true, response.body)
      else
        parse(false, "#{response.code}: #{response.body}")
      end
    rescue Exception
      message = "#{$!.class}: #{$!.message}\n"
      message <<  $@.join("\n")
      parse(false, message)
    end
  else
    groonga = "#{@groonga} -p #{@port} -c #{@host}"
    result = `#{groonga} #{command} #{args.join(' ')} 2>&1`
    parse($?.success?, result)
  end
end

def parse_list(header, list)
  list.collect do |item|
    parsed_item = {}
    header.each_with_index do |(name, type), i|
      parsed_item[name] = item[i]
    end
    parsed_item
  end
end

case command
when "autoconf", "detect"
  success, body = run("status")
  if success
    puts "yes"
    exit(true)
  else
    puts "no (#{body})"
    exit(false)
  end
when "config"
  if label.nil?
    title = "groonga: throughput"
  else
    title = "groonga: #{label}: throughput"
  end
  puts <<EOF
graph_title #{title}
graph_vlabel queries per ${graph_period}
graph_category groonga
graph_info groonga throughput

n_queries.label N queries
n_queries.type COUNTER
EOF
  exit(true)
end

success, body = run("status")
unless success
  puts("error: #{body}")
  exit(false)
end
puts <<EOF
n_queries.value #{body["n_queries"]}
EOF
