#!/usr/bin/env ruby

require 'mcollective'

include MCollective::RPC

options = rpcoptions do |parser, options|
    parser.define_head "Report on usage for a specific fact"
    parser.banner = "Usage: mc-facts [options] fact"
end

if ARGV.length > 0
    fact = ARGV.shift
else
    puts("Please specify a fact to report")
    exit 1
end

def show_single_fact_report(fact, facts, verbose=false)
    puts("Report for fact: #{fact}\n\n")

    facts.keys.sort.each do |k|
        printf("        %-40sfound %d times\n", k, facts[k].size)

        if verbose
            puts

            facts[k].sort.each do |f|
                puts("            #{f}")
            end

            puts
        end
    end
end

begin
    rpcutil = rpcclient("rpcutil", :options => options)
    rpcutil.progress = false

    facts = {}

    rpcutil.get_fact(:fact => fact) do |resp|
        value = resp[:body][:data][:value]
        if value
            facts.include?(value) ? facts[value] << resp[:senderid] : facts[value] = [ resp[:senderid] ]
        end
    end

    show_single_fact_report(fact, facts, options[:verbose])
rescue Exception => e
    STDERR.puts "Could not call remote agent: #{e}"
    exit 1
end


printrpcstats

rpcutil.disconnect

# vi:tabstop=4:expandtab:ai
