module Onering module CLI module Devices def self.configure(global={}) @api = Onering::CLI.connect(global).devices @opts = ::Trollop::options do banner <<-EOS Options: EOS opt :query, "The Onering urlquery to filter devices by", :short => '-f', :type => :string opt :id, "The node ID of the device to operate on", :short => '-i', :type => :string # subcommands stop_on %w{show get set list find save} end end def self.run(args) sc = args.shift case (sc.downcase.to_sym rescue nil) # ----------------------------------------------------------------------------- when :show return @api.devices.show(args[0]) # ----------------------------------------------------------------------------- when :get raise "Expected 1 parameter, got #{args.length}" unless args.length == 1 if @opts[:query_given] # doing this until a bulk field query endpoint is built return @api.list('id', { :filter => @opts[:query] }).collect{|i| @api.get_field(i, args[0])} elsif @opts[:id_given] return @api.get_field(@opts[:id], args[0]) end # ----------------------------------------------------------------------------- when :set raise "Expected 2 parameters, got #{args.length}" unless args.length == 2 if @opts[:query] # doing this until a bulk field set endpoint is built return @api.list('id', { :filter => @opts[:query] }).collect{|i| @api.set_field(i, args[0])} elsif @opts[:id] return @api.set_field(@opts[:id], args[0], args[1]) end # ----------------------------------------------------------------------------- when :list raise "Expected 1 parameter, got #{args.length}" unless args.length >= 1 return @api.list(args[0], { :filter => [@opts[:query], args[1]].compact.join('/') }.compact) # ----------------------------------------------------------------------------- when :find raise "Expected 1 parameter, got #{args.length}" unless args.length == 1 return @api.find(args[0]) # ----------------------------------------------------------------------------- when :save rv = @api.save(args[0] || @opts[:id]) do # read from pipe if not STDIN.tty? STDIN.read # read from specified file elsif (File.readable?(args[1]) rescue false) File.read(args[1]) else raise "Cannot save data, no input data specified" end end rv.parsed_response else raise "Unknown subcommand #{sc.inspect}" end end end end end