#!/usr/bin/env ruby

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

require 'shellwords'
require 'json'

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

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 @path
    path = Shellwords.shellescape(@path)
    result = `#{@groonga} #{path} #{command} #{args.join(' ')} 2>&1`
  else
    groonga = "#{@groonga} -p #{@port} -c #{@host}"
    result = `#{groonga} #{command} #{args.join(' ')} 2>&1`
  end
  parse($?.success?, result)
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: number of records"
  else
    title = "groonga: #{label}: number of records"
  end
  puts <<EOF
graph_title #{title}
graph_vlabel records
graph_category groonga
graph_info number of records in groonga table
EOF
  success, body = run("table_list")
  unless success
    puts "error: #{body}"
    exit(false)
  end
  parse_list(body[0], body[1..-1]).each do |table|
    name = table["name"]
    puts <<EOF

#{name}.label #{name}
#{name}.type GAUGE
EOF
  end
  exit(true)
end

success, body = run("table_list")
unless success
  puts("error: #{body}")
  exit(false)
end
parse_list(body[0], body[1..-1]).each do |table|
  name = table["name"]
  success, body = run("select", "#{name} --limit 0")
  unless success
    puts("error: #{body}")
    exit(false)
  end
  n_records = body[0][0][0]
  puts <<EOF
#{name}.value #{n_records}
EOF
end
