Class: Morpheus::Cli::NetworksCommand

Inherits:
Object
  • Object
show all
Includes:
CliCommand, InfrastructureHelper
Defined in:
lib/morpheus/cli/networks_command.rb

Instance Attribute Summary

Attributes included from CliCommand

#no_prompt

Instance Method Summary collapse

Methods included from InfrastructureHelper

#cloud_type_for_id, #cloud_type_for_name, #cloud_type_for_name_or_id, #clouds_interface, #find_cloud_by_id, #find_cloud_by_name, #find_cloud_by_name_or_id, #find_group_by_id, #find_group_by_name, #find_group_by_name_or_id, #get_available_cloud_types, #groups_interface, included

Methods included from CliCommand

#build_common_options, #build_option_type_options, #command_name, #default_subcommand, #establish_remote_appliance_connection, #full_command_usage, #handle_subcommand, included, #interactive?, #my_help_command, #my_terminal, #my_terminal=, #parse_id_list, #parse_list_options, #parse_list_subtitles, #print, #print_error, #puts, #puts_error, #raise_command_error, #run_command_for_each_arg, #subcommand_aliases, #subcommand_usage, #subcommands, #usage, #verify_access_token!

Constructor Details

#initializeNetworksCommand

set_default_subcommand :list



18
19
20
# File 'lib/morpheus/cli/networks_command.rb', line 18

def initialize()
  # @appliance_name, @appliance_url = Morpheus::Cli::Remote.active_appliance
end

Instance Method Details

#add(args) ⇒ Object



193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
# File 'lib/morpheus/cli/networks_command.rb', line 193

def add(args)
  options = {}
  network_type_id = nil
  tenants = nil
  group_access_all = nil
  group_access_list = nil
  group_defaults_list = nil
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("-t TYPE")
    opts.on( '-c', '--cloud CLOUD', "Cloud Name or ID" ) do |val|
      options[:cloud] = val
    end
    opts.on('-t', '--type ID', "Network Type Name or ID") do |val|
      options['type'] = val
    end
    opts.on('--name VALUE', String, "Name for this network") do |val|
      options['name'] = val
    end
    opts.on('--description VALUE', String, "Description of network") do |val|
      options['description'] = val
    end
    opts.on('--gateway VALUE', String, "Gateway") do |val|
      options['gateway'] = val
    end
    opts.on('--dns-primary VALUE', String, "DNS Primary") do |val|
      options['dnsPrimary'] = val
    end
    opts.on('--dns-secondary VALUE', String, "DNS Secondary") do |val|
      options['dnsSecondary'] = val
    end
    opts.on('--cidr VALUE', String, "CIDR") do |val|
      options['cidr'] = val
    end
    opts.on('--vlan-id VALUE', String, "VLAN ID") do |val|
      options['vlanId'] = val.to_i
    end
    opts.on('--pool ID', String, "Network Pool") do |val|
      options['pool'] = val.to_i
    end
    opts.on('--dhcp-server [on|off]', String, "DHCP Server") do |val|
      options['dhcpServer'] = val.to_s == 'on' || val.to_s == 'true'
    end
    opts.on('--allow-ip-override [on|off]', String, "Allow IP Override") do |val|
      options['allowStaticOverride'] = val.to_s == 'on' || val.to_s == 'true'
    end
    opts.on('--group-access-all [on|off]', String, "Toggle Access for all groups.") do |val|
      group_access_all = val.to_s == 'on' || val.to_s == 'true'
    end
    opts.on('--group-access LIST', Array, "Group Access, comma separated list of group IDs.") do |list|
      if list.size == 1 && list[0] == 'null' # hacky way to clear it
        group_access_list = []
      else
        group_access_list = list.collect {|it| it.to_s.strip.empty? ? nil : it.to_s.strip }.compact.uniq
      end
    end
    opts.on('--group-defaults LIST', Array, "Group Default Selection, comma separated list of group IDs") do |list|
      if list.size == 1 && list[0] == 'null' # hacky way to clear it
        group_defaults_list = []
      else
        group_defaults_list = list.collect {|it| it.to_s.strip.empty? ? nil : it.to_s.strip }.compact.uniq
      end
    end
    opts.on('--tenants LIST', Array, "Tenant Access, comma separated list of account IDs") do |list|
      if list.size == 1 && list[0] == 'null' # hacky way to clear it
        options['tenants'] = []
      else
        options['tenants'] = list.collect {|it| it.to_s.strip.empty? ? nil : it.to_s.strip }.compact.uniq
      end
    end
    opts.on('--accounts LIST', Array, "alias for --tenants") do |list|
      if list.size == 1 && list[0] == 'null' # hacky way to clear it
        options['tenants'] = []
      else
        options['tenants'] = list.collect {|it| it.to_s.strip.empty? ? nil : it.to_s.strip }.compact.uniq
      end
    end
    opts.on('--visibility [private|public]', String, "Visibility") do |val|
      options['visibility'] = val
    end
    opts.on('--active [on|off]', String, "Can be used to disable a network") do |val|
      options['active'] = val.to_s == 'on' || val.to_s == 'true'
    end
    build_common_options(opts, options, [:options, :payload, :json, :dry_run, :quiet, :remote])
    opts.footer = "Create a new network." + "\n" +
                  "[name] is required and can be passed as --name instead."
  end
  optparse.parse!(args)
  if args.count > 1
    print_error Morpheus::Terminal.angry_prompt
    puts_error  "wrong number of arguments, expected 0-1 and got #{args.count}\n#{optparse}"
    return 1
  end
  connect(options)
  begin
    # merge -O options into normally parsed options
    options.deep_merge!(options[:options].reject {|k,v| k.is_a?(Symbol) }) if options[:options]

    # support [name] as first argument
    if args[0]
      options['name'] = args[0]
    end

    # construct payload
    payload = nil
    if options[:payload]
      payload = options[:payload]
    else
      # prompt for network options
      payload = {
        'network' => {
          # 'config' => {}
        }
      }
      
      # allow arbitrary -O options
      payload['network'].deep_merge!(options[:options].reject {|k,v| k.is_a?(Symbol) }) if options[:options]

      # Cloud
      cloud = nil
      if options[:cloud]
        cloud = find_cloud_by_name_or_id(options[:cloud])
        # meh, should validate cloud is in the cloudsForNetworks dropdown..
        return 1 if cloud.nil?
      else
        # print_red_alert "Cloud not specified!"
        # exit 1
        cloud_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'cloud', 'type' => 'select', 'fieldLabel' => 'Cloud', 'optionSource' => 'cloudsForNetworks', 'required' => true, 'description' => 'Select Cloud.'}],options,@api_client,{})
        cloud_id = cloud_prompt['cloud']
        cloud = find_cloud_by_name_or_id(cloud_id) if cloud_id
        return 1 if cloud.nil?
      end
      payload['network']['zone'] = {'id' => cloud['id']}

      # Network Type
      network_type_id = nil
      api_params = {"network.zone.id" => cloud['id']} #{network:{zone:{id: cloud['id']}}}
      v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'type', 'fieldLabel' => 'Network Type', 'type' => 'select', 'optionSource' => 'networkTypesForCloud', 'required' => true, 'description' => 'Choose a network type.'}], options, @api_client, api_params)
      network_type_id = v_prompt['type']
      if network_type_id.nil? || network_type_id.to_s.empty?
        print_red_alert "Network Type not found by id '#{options['type']}'"
        return 1
      end
      payload['network']['type'] = {'id' => network_type_id.to_i }

      # Name
      if options['name']
        payload['network']['name'] = options['name']
      else
        v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'name', 'fieldLabel' => 'Name', 'type' => 'text', 'required' => true, 'description' => 'Name for this network.'}], options)
        payload['network']['name'] = v_prompt['name']
      end

      # Description
      if options['description']
        payload['network']['description'] = options['description']
      else
        v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'description', 'fieldLabel' => 'Description', 'type' => 'text', 'required' => false, 'description' => 'Description of network.'}], options)
        payload['network']['description'] = v_prompt['description']
      end

      # Gateway
      if options['gateway']
        payload['network']['gateway'] = options['gateway']
      else
        v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'gateway', 'fieldLabel' => 'Gateway', 'type' => 'text', 'required' => false, 'description' => ''}], options)
        payload['network']['gateway'] = v_prompt['gateway']
      end

      # DNS Primary
      if options['dnsPrimary']
        payload['network']['dnsPrimary'] = options['dnsPrimary']
      else
        v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'dnsPrimary', 'fieldLabel' => 'DNS Primary', 'type' => 'text', 'required' => false, 'description' => ''}], options)
        payload['network']['dnsPrimary'] = v_prompt['dnsPrimary']
      end

      # DNS Secondary
      if options['dnsSecondary']
        payload['network']['dnsSecondary'] = options['dnsSecondary']
      else
        v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'dnsSecondary', 'fieldLabel' => 'DNS Secondary', 'type' => 'text', 'required' => false, 'description' => ''}], options)
        payload['network']['dnsSecondary'] = v_prompt['dnsSecondary']
      end

      # CIDR
      if options['cidr']
        payload['network']['cidr'] = options['cidr']
      else
        v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'cidr', 'fieldLabel' => 'CIDR', 'type' => 'text', 'required' => false, 'description' => ''}], options)
        payload['network']['cidr'] = v_prompt['cidr']
      end

      # VLAN ID
      if options['vlanId']
        payload['network']['vlanId'] = options['vlanId']
      else
        v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'vlanId', 'fieldLabel' => 'VLAN ID', 'type' => 'number', 'required' => false, 'description' => ''}], options)
        payload['network']['vlanId'] = v_prompt['vlanId']
      end

      # Network Pool
      if options['pool']
        payload['network']['pool'] = options['pool'].to_i
      else
        # todo: select dropdown
        # v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'pool', 'fieldLabel' => 'Network Pool', 'type' => 'select', 'optionSource' => 'networkPools', 'required' => false, 'description' => ''}], options, @api_client, {zoneId: cloud['id']})
        v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'pool', 'fieldLabel' => 'Network Pool', 'type' => 'text', 'required' => false, 'description' => ''}], options)
        payload['network']['pool'] = v_prompt['pool'].to_i if v_prompt['pool']
      end

      # DHCP Server
      if options['dhcpServer'] != nil
        payload['network']['dhcpServer'] = options['dhcpServer']
      else
        v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'dhcpServer', 'fieldLabel' => 'DHCP Server', 'type' => 'checkbox', 'required' => false, 'description' => ''}], options)
        payload['network']['dhcpServer'] = v_prompt['dhcpServer']
      end

      # Allow IP Override
      if options['allowStaticOverride'] != nil
        payload['network']['allowStaticOverride'] = options['allowStaticOverride']
      else
        v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'allowStaticOverride', 'fieldLabel' => 'Allow IP Override', 'type' => 'checkbox', 'required' => false, 'description' => ''}], options)
        payload['network']['allowStaticOverride'] = v_prompt['allowStaticOverride']
      end
    
      # Group Access
      if group_access_all != nil
        payload['resourcePermissions'] ||= {}
        payload['resourcePermissions']['all'] = group_access_all
      end
      if group_access_list != nil
        payload['resourcePermissions'] ||= {}
        payload['resourcePermissions']['sites'] = group_access_list.collect do |site_id|
          site = {"id" => site_id.to_i}
          if group_defaults_list && group_defaults_list.include?(site_id)
            site["default"] = true
          end
          site
        end
      end

      # Tenants
      if options['tenants']
        payload['tenantPermissions'] = {}
        payload['tenantPermissions']['accounts'] = options['tenants']
      end

      # Active
      if options['active'] != nil
        payload['network']['active'] = options['active']
      end
      
      # Visibility
      if options['visibility'] != nil
        payload['network']['visibility'] = options['visibility']
      end

    end

    
    if options[:dry_run]
      print_dry_run @networks_interface.dry.create(payload)
      return
    end
    json_response = @networks_interface.create(payload)
    if options[:json]
      print JSON.pretty_generate(json_response)
      print "\n"
    elsif !options[:quiet]
      network = json_response['network']
      print_green_success "Added network #{network['name']}"
      get([network['id']])
    end
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#connect(opts) ⇒ Object



22
23
24
25
26
27
# File 'lib/morpheus/cli/networks_command.rb', line 22

def connect(opts)
  @api_client = establish_remote_appliance_connection(opts)
  @networks_interface = @api_client.networks
  @clouds_interface = @api_client.clouds
  @options_interface = @api_client.options
end

#get(args) ⇒ Object



102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
# File 'lib/morpheus/cli/networks_command.rb', line 102

def get(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[network]")
    build_common_options(opts, options, [:json, :yaml, :csv, :fields, :dry_run, :remote])
    opts.footer = "Get details about a network." + "\n" +
                  "[network] is required. This is the name or id of a network."
  end
  optparse.parse!(args)
  if args.count != 1
    print_error Morpheus::Terminal.angry_prompt
    puts_error  "#{command_name} missing argument: [network]\n#{optparse}"
    return 1
  end
  connect(options)
  begin
    if options[:dry_run]
      if args[0].to_s =~ /\A\d{1,}\Z/
        print_dry_run @networks_interface.dry.get(args[0].to_i)
      else
        print_dry_run @networks_interface.dry.list({name:args[0]})
      end
      return
    end
    network = find_network_by_name_or_id(args[0])
    return 1 if network.nil?
    json_response = {'network' => network}  # skip redundant request
    # json_response = @networks_interface.get(network['id'])
    network = json_response['network']
    if options[:json]
      puts as_json(json_response, options, "network")
      return 0
    elsif options[:yaml]
      puts as_yaml(json_response, options, "network")
      return 0
    elsif options[:csv]
      puts records_as_csv([network], options)
      return 0
    end
    print_h1 "Network Details"
    print cyan
    description_cols = {
      "ID" => 'id',
      "Name" => 'name',
      "Description" => 'description',
      "Type" => lambda {|it| it['type'] ? it['type']['name'] : '' },
      "Cloud" => lambda {|it| it['zone'] ? it['zone']['name'] : '' },
      "CIDR" => 'cidr',
      "Gateway" => 'gateway',
      "Netmask" => 'netmask',
      "Subnet" => 'subnetAddress',
      "Primary DNS" => 'dnsPrimary',
      "Secondary DNS" => 'dnsSecondary',
      "Pool" => lambda {|it| it['pool'] ? it['pool']['name'] : '' },
      "DHCP" => lambda {|it| it['dhcpServer'] ? 'Yes' : 'No' },
      "Allow IP Override" => lambda {|it| it['allowStaticOverride'] ? 'Yes' : 'No' },
      "Visibility" => lambda {|it| it['visibility'].to_s.capitalize },
      "Tenants" => lambda {|it| it['tenants'] ? it['tenants'].collect {|it| it['name'] }.uniq.join(', ') : '' },
      # "Owner" => lambda {|it| it['owner'] ? it['owner']['name'] : '' },
    }
    print_description_list(description_cols, network)

    if network['resourcePermission'].nil?
      print "\n", "No group access found", "\n"
    else
      print_h2 "Group Access"
      rows = []
      if network['resourcePermission']['all']
        rows.push({"name" => 'All'})
      end
      if network['resourcePermission']['sites']
        network['resourcePermission']['sites'].each do |site|
          rows.push(site)
        end
      end
      rows = rows.collect do |site|
        {group: site['name'], default: site['default'] ? 'Yes' : ''}
      end
      columns = [:group, :default]
      print cyan
      print as_pretty_table(rows, columns)
    end

    print reset,"\n"
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    return 1
  end
end

#handle(args) ⇒ Object



29
30
31
# File 'lib/morpheus/cli/networks_command.rb', line 29

def handle(args)
  handle_subcommand(args)
end

#list(args) ⇒ Object



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
# File 'lib/morpheus/cli/networks_command.rb', line 33

def list(args)
  options = {}
  params = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage()
    opts.on('--cidr VALUE', String, "Filter by cidr, matches beginning of value.") do |val|
      params['cidr'] = val
    end
    build_common_options(opts, options, [:list, :json, :yaml, :csv, :fields, :json, :dry_run, :remote])
    opts.footer = "List networks."
  end
  optparse.parse!(args)
  connect(options)
  begin
    params.merge!(parse_list_options(options))
    if options[:dry_run]
      print_dry_run @networks_interface.dry.list(params)
      return
    end
    json_response = @networks_interface.list(params)
    networks = json_response["networks"]
    if options[:json]
      puts as_json(json_response, options, "networks")
      return 0
    elsif options[:yaml]
      puts as_yaml(json_response, options, "networks")
      return 0
    elsif options[:csv]
      puts records_as_csv(networks, options)
      return 0
    end
    title = "Morpheus Networks"
    subtitles = []
    subtitles += parse_list_subtitles(options)
    print_h1 title, subtitles
    if networks.empty?
      print cyan,"No networks found.",reset,"\n"
    else
      rows = networks.collect {|network| 
        row = {
          id: network['id'],
          name: network['name'],
          type: network['type'] ? network['type']['name'] : '',
          cloud: network['zone'] ? network['zone']['name'] : '',
          cidr: network['cidr'],
          pool: network['pool'] ? network['pool']['name'] : '',
          dhcp: network['dhcpServer'] ? 'Yes' : 'No',
          visibility: network['visibility'].to_s.capitalize,
          tenants: network['tenants'] ? network['tenants'].collect {|it| it['name'] }.uniq.join(', ') : ''
        }
        row
      }
      columns = [:id, :name, :type, :cloud, :cidr, :pool, :dhcp, :visibility, :tenants]
      if options[:include_fields]
        columns = options[:include_fields]
      end
      print cyan
      print as_pretty_table(rows, columns, options)
      print reset
      print_results_pagination(json_response, {:label => "network", :n_label => "networks"})
    end
    print reset,"\n"
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#remove(args) ⇒ Object



751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
# File 'lib/morpheus/cli/networks_command.rb', line 751

def remove(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[network]")
    build_common_options(opts, options, [:account, :auto_confirm, :json, :dry_run, :remote])
    opts.footer = "Delete a network." + "\n" +
                  "[network] is required. This is the name or id of a network."
  end
  optparse.parse!(args)

  if args.count < 1
    print_error Morpheus::Terminal.angry_prompt
    puts_error  "#{command_name} missing argument: [network]\n#{optparse}"
    return 1
  end

  connect(options)
  begin
    network = find_network_by_name_or_id(args[0])
    return 1 if network.nil?

    unless options[:yes] || Morpheus::Cli::OptionTypes.confirm("Are you sure you want to delete the network: #{network['name']}?")
      return 9, "aborted command"
    end
    if options[:dry_run]
      print_dry_run @networks_interface.dry.destroy(network['id'])
      return 0
    end
    json_response = @networks_interface.destroy(network['id'])
    if options[:json]
      print JSON.pretty_generate(json_response)
      print "\n"
    else
      print_green_success "Removed network #{network['name']}"
      # list([])
    end
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    return 1
  end
end

#update(args) ⇒ Object



474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
# File 'lib/morpheus/cli/networks_command.rb', line 474

def update(args)
  options = {}
  # network_type_id = nil
  tenants = nil
  group_access_all = nil
  group_access_list = nil
  group_defaults_list = nil
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[network] [options]")
    # opts.on( '-c', '--cloud CLOUD', "Cloud Name or ID" ) do |val|
    #   options[:cloud] = val
    # end
    # opts.on('-t', '--type ID', "Network Type Name or ID") do |val|
    #   options['type'] = val
    # end
    opts.on('--name VALUE', String, "Name for this network") do |val|
      options['name'] = val
    end
    opts.on('--description VALUE', String, "Description of network") do |val|
      options['description'] = val
    end
    opts.on('--gateway VALUE', String, "Gateway") do |val|
      options['gateway'] = val
    end
    opts.on('--dns-primary VALUE', String, "DNS Primary") do |val|
      options['dnsPrimary'] = val
    end
    opts.on('--dns-secondary VALUE', String, "DNS Secondary") do |val|
      options['dnsSecondary'] = val
    end
    opts.on('--cidr VALUE', String, "CIDR") do |val|
      options['cidr'] = val
    end
    opts.on('--vlan-id VALUE', String, "VLAN ID") do |val|
      options['vlanId'] = val.to_i
    end
    opts.on('--pool ID', String, "Network Pool") do |val|
      options['pool'] = val.to_i
    end
    opts.on('--dhcp-server [on|off]', String, "DHCP Server") do |val|
      options['dhcpServer'] = val.to_s == 'on' || val.to_s == 'true'
    end
    opts.on('--allow-ip-override [on|off]', String, "Allow IP Override") do |val|
      options['allowStaticOverride'] = val.to_s == 'on' || val.to_s == 'true'
    end
    opts.on('--group-access-all [on|off]', String, "Toggle Access for all groups.") do |val|
      group_access_all = val.to_s == 'on' || val.to_s == 'true'
    end
    opts.on('--group-access LIST', Array, "Group Access, comma separated list of group IDs.") do |list|
      if list.size == 1 && list[0] == 'null' # hacky way to clear it
        group_access_list = []
      else
        group_access_list = list.collect {|it| it.to_s.strip.empty? ? nil : it.to_s.strip }.compact.uniq
      end
    end
    opts.on('--group-defaults LIST', Array, "Group Default Selection, comma separated list of group IDs") do |list|
      if list.size == 1 && list[0] == 'null' # hacky way to clear it
        group_defaults_list = []
      else
        group_defaults_list = list.collect {|it| it.to_s.strip.empty? ? nil : it.to_s.strip }.compact.uniq
      end
    end
    opts.on('--tenants LIST', Array, "Tenant Access, comma separated list of account IDs") do |list|
      if list.size == 1 && list[0] == 'null' # hacky way to clear it
        options['tenants'] = []
      else
        options['tenants'] = list.collect {|it| it.to_s.strip.empty? ? nil : it.to_s.strip }.compact.uniq
      end
    end
    opts.on('--accounts LIST', Array, "alias for --tenants") do |list|
      if list.size == 1 && list[0] == 'null' # hacky way to clear it
        options['tenants'] = []
      else
        options['tenants'] = list.collect {|it| it.to_s.strip.empty? ? nil : it.to_s.strip }.compact.uniq
      end
    end
    opts.on('--visibility [private|public]', String, "Visibility") do |val|
      options['visibility'] = val
    end
    opts.on('--active [on|off]', String, "Can be used to disable a network") do |val|
      options['active'] = val.to_s == 'on' || val.to_s == 'true'
    end
    build_common_options(opts, options, [:options, :payload, :json, :dry_run, :remote])
    opts.footer = "Update a network." + "\n" +
                  "[network] is required. This is the id of a network."
  end
  optparse.parse!(args)
  if args.count != 1
    print_error Morpheus::Terminal.angry_prompt
    puts_error  "wrong number of arguments, expected 1 and got #{args.count}\n#{optparse}"
    return 1
  end
  connect(options)

  begin
    network = find_network_by_name_or_id(args[0])
    return 1 if network.nil?
    
    # merge -O options into normally parsed options
    options.deep_merge!(options[:options].reject {|k,v| k.is_a?(Symbol) }) if options[:options]

    # construct payload
    payload = nil
    if options[:payload]
      payload = options[:payload]
    else
      # prompt for network options
      payload = {
        'network' => {
          # 'config' => {}
        }
      }
      
      # allow arbitrary -O options
      payload['network'].deep_merge!(options[:options].reject {|k,v| k.is_a?(Symbol) }) if options[:options]

      # # Cloud
      # cloud = nil
      # if options[:cloud]
      #   cloud = find_cloud_by_name_or_id(options[:cloud])
      #   # meh, should validate cloud is in the cloudsForNetworks dropdown..
      #   return 1 if cloud.nil?
      # else
      #   # print_red_alert "Cloud not specified!"
      #   # exit 1
      #   cloud_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'cloud', 'type' => 'select', 'fieldLabel' => 'Cloud', 'optionSource' => 'cloudsForNetworks', 'required' => true, 'description' => 'Select Cloud.'}],options,@api_client,{})
      #   cloud_id = cloud_prompt['cloud']
      #   cloud = find_cloud_by_name_or_id(cloud_id) if cloud_id
      #   return 1 if cloud.nil?
      # end

      # # Network Type
      # network_type_id = nil
      # api_params = {"network.zone.id" => cloud['id']} #{network:{zone:{id: cloud['id']}}}
      # v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'type', 'fieldLabel' => 'Network Type', 'type' => 'select', 'optionSource' => 'networkTypesForCloud', 'required' => true, 'description' => 'Choose a network type.'}], options, @api_client, api_params)
      # network_type_id = v_prompt['type']
      # if network_type_id.nil? || network_type_id.to_s.empty?
      #   print_red_alert "Network Type not found by id '#{options['type']}'"
      #   return 1
      # end
      # payload['network']['type'] = {'id' => network_type_id.to_i }

      # Name
      if options['name']
        payload['network']['name'] = options['name']
      else
        # v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'name', 'fieldLabel' => 'Name', 'type' => 'text', 'required' => true, 'description' => 'Name for this network.'}], options)
        # payload['network']['name'] = v_prompt['name']
      end

      # Description
      if options['description']
        payload['network']['description'] = options['description']
      else
        # v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'description', 'fieldLabel' => 'Description', 'type' => 'text', 'required' => false, 'description' => 'Description of network.'}], options)
        # payload['network']['description'] = v_prompt['description']
      end

      # Gateway
      if options['gateway']
        payload['network']['gateway'] = options['gateway']
      else
        # v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'gateway', 'fieldLabel' => 'Gateway', 'type' => 'text', 'required' => false, 'description' => ''}], options)
        # payload['network']['gateway'] = v_prompt['gateway']
      end

      # DNS Primary
      if options['dnsPrimary']
        payload['network']['dnsPrimary'] = options['dnsPrimary']
      else
        # v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'dnsPrimary', 'fieldLabel' => 'DNS Primary', 'type' => 'text', 'required' => false, 'description' => ''}], options)
        # payload['network']['dnsPrimary'] = v_prompt['dnsPrimary']
      end

      # DNS Secondary
      if options['dnsSecondary']
        payload['network']['dnsSecondary'] = options['dnsSecondary']
      else
        # v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'dnsSecondary', 'fieldLabel' => 'DNS Secondary', 'type' => 'text', 'required' => false, 'description' => ''}], options)
        # payload['network']['dnsSecondary'] = v_prompt['dnsSecondary']
      end

      # CIDR
      if options['cidr']
        payload['network']['cidr'] = options['cidr']
      else
        # v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'cidr', 'fieldLabel' => 'CIDR', 'type' => 'text', 'required' => false, 'description' => ''}], options)
        # payload['network']['cidr'] = v_prompt['cidr']
      end

      # VLAN ID
      if options['vlanId']
        payload['network']['vlanId'] = options['vlanId']
      else
        # v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'vlanId', 'fieldLabel' => 'VLAN ID', 'type' => 'number', 'required' => false, 'description' => ''}], options)
        # payload['network']['vlanId'] = v_prompt['vlanId']
      end

      # Network Pool
      if options['pool']
        payload['network']['pool'] = options['pool'].to_i
      else
        # todo: select dropdown
        # v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'pool', 'fieldLabel' => 'Network Pool', 'type' => 'select', 'optionSource' => 'networkPools', 'required' => false, 'description' => ''}], options, @api_client, {zoneId: cloud['id']})
        # v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'pool', 'fieldLabel' => 'Network Pool', 'type' => 'text', 'required' => false, 'description' => ''}], options)
        # payload['network']['pool'] = v_prompt['pool'].to_i if v_prompt['pool']
      end

      # DHCP Server
      if options['dhcpServer'] != nil
        payload['network']['dhcpServer'] = options['dhcpServer']
      else
        # v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'dhcpServer', 'fieldLabel' => 'DHCP Server', 'type' => 'checkbox', 'required' => false, 'description' => ''}], options)
        # payload['network']['dhcpServer'] = v_prompt['dhcpServer']
      end

      # Allow IP Override
      if options['allowStaticOverride'] != nil
        payload['network']['allowStaticOverride'] = options['allowStaticOverride']
      else
        # v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'allowStaticOverride', 'fieldLabel' => 'Allow IP Override', 'type' => 'checkbox', 'required' => false, 'description' => ''}], options)
        # payload['network']['allowStaticOverride'] = v_prompt['allowStaticOverride']
      end
    
      # Group Access
      if group_access_all != nil
        payload['resourcePermissions'] ||= {}
        payload['resourcePermissions']['all'] = group_access_all
      end
      if group_access_list != nil
        payload['resourcePermissions'] ||= {}
        payload['resourcePermissions']['sites'] = group_access_list.collect do |site_id|
          site = {"id" => site_id.to_i}
          if group_defaults_list && group_defaults_list.include?(site_id)
            site["default"] = true
          end
          site
        end
      end

      # Tenants
      if options['tenants']
        payload['tenantPermissions'] = {}
        payload['tenantPermissions']['accounts'] = options['tenants']
      end

      # Active
      if options['active'] != nil
        payload['network']['active'] = options['active']
      end
      
      # Visibility
      if options['visibility'] != nil
        payload['network']['visibility'] = options['visibility']
      end

    end

    if options[:dry_run]
      print_dry_run @networks_interface.dry.update(network["id"], payload)
      return
    end
    json_response = @networks_interface.update(network["id"], payload)
    if options[:json]
      puts as_json(json_response)
    else
      network = json_response['network']
      print_green_success "Updated network #{network['name']}"
      get([network['id']])
    end
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    return 1
  end
end