#!/usr/bin/env ruby
#
#  equityctl - management client for equity
#
#  Usage: equityctl [<host>:]<port> <command>
#
#  The host defaults to localhost.
#
#  Command    Description
#  status     Displays each node's address, port, connection status, and
#             connection counter.
#
#  Equity uses UDP packets to send control information, so all of UDP's caveats
#  apply to equityctl.
#

require 'equity/controller'

# Process arguments.
if ARGV.length != 2
  STDERR.puts 'Usage: equityctl [<host>:]<port> <command>'
  STDERR.print "\n"
  STDERR.puts 'The host defaults to localhost.'
  STDERR.print "\n"
  STDERR.puts 'Command    Description'
  STDERR.puts 'status     Displays each node\'s address, port, connection status,'
  STDERR.puts '           connection counter, and failure counter.'
  exit(64) # EX_USAGE
end

address, port = ARGV.shift.split(':', 2)
if port.nil?
  port = address
  address = 'localhost'
end

command = ARGV.shift

# Send command.
class NoResponseError < Exception; end

controller = Equity::Controller.new(address, port.to_i)
begin
  case command
  when 'status'
    nodes = controller.node_status || raise(NoResponseError)
    nodes.each do |node|
      puts "#{node} #{node.connected? ? 'C' : '-'} #{node.counter} #{node.failure_counter}"
    end
  else
    STDERR.puts "Unrecognized command: #{command}"
    STDERR.puts 'Run equityctl with no arguments for a list of commands.'
    exit(64)
  end
rescue NoResponseError
  STDERR.puts "No response from #{address}:#{port}"
  exit(1)
end
