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 Onering::Logger.fatal!("Expected 1 parameter, got #{args.length}", "Onering::CLI::Devices") 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 Onering::Logger.fatal!("Expected 2 parameters, got #{args.length}", "Onering::CLI::Devices") 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 Onering::Logger.fatal!("Expected 1 parameter, got #{args.length}", "Onering::CLI::Devices") unless args.length >= 1 return @api.list(args[0], { :filter => [@opts[:query], args[1]].compact.join('/') }.compact) # ----------------------------------------------------------------------------- when :find Onering::Logger.fatal!("Expected 1 parameter, got #{args.length}", "Onering::CLI::Devices") 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 Onering::Logger.fatal!("Cannot save data, no input data specified", "Onering::CLI::Devices") end end rv.parsed_response else Onering::Logger.fatal!("Unknown subcommand #{sc.inspect}", "Onering::CLI::Devices") end end end end end