#!/usr/bin/env ruby
# Client program for the mcollective instance kill agent
#
#   Copyright 2011 Canonical Ltd.
#   Author: Marc Cluet
#
#   Licensed under the Apache License, Version 2.0 (the "License");
#   you may not use this file except in compliance with the License.
#   You may obtain a copy of the License at
#
#       http://www.apache.org/licenses/LICENSE-2.0
#
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS,
#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#   See the License for the specific language governing permissions and
#   limitations under the License.
# 

require 'mcollective'

include MCollective::RPC

options = rpcoptions do |parser, options|
    parser.define_head "Manage puppet on Ubuntu"
    parser.banner = "Usage: mc-kill [-options] [kill|forcekill]"

    parser.separator ""
    parser.separator "Run Options"
end

killrpc = rpcclient("kill", {:options => options})

def log(msg)
    puts("#{Time.now} - #{msg}")
end

def summarize(stats)
    puts("\n---- kill agent summary ----")
    puts("           Nodes: #{stats[:discovered]} / #{stats[:responses]}")
    printf("    Elapsed Time: %.2f s\n\n", stats[:blocktime])
end

if  ARGV.length == 1
    action = ARGV.shift

    unless action =~ /^(kill|forcekill)$/
        puts("Action has to be kill or forcekill")
        exit 1
    end
    killrpc.send(action).each do |node|
        begin
            printf("%-40s %s\n", node[:sender], node[:statusmsg])
        rescue StandardError => e
            log "The RPC agent #{node[:sender]} returned an error: #{e}"
        end
    end
else
    puts("Usage: mc-kill [-options] [kill|forcekill]")
    exit 1
end

summarize(killrpc.stats)

killrpc.disconnect
# vi:tabstop=4:expandtab:ai
