1/*
2Copyright (c) 2014-2016 VMware, Inc. All Rights Reserved.
3
4Licensed under the Apache License, Version 2.0 (the "License");
5you may not use this file except in compliance with the License.
6You may obtain a copy of the License at
7
8    http://www.apache.org/licenses/LICENSE-2.0
9
10Unless required by applicable law or agreed to in writing, software
11distributed under the License is distributed on an "AS IS" BASIS,
12WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13See the License for the specific language governing permissions and
14limitations under the License.
15*/
16
17package serial
18
19import (
20	"context"
21	"flag"
22	"fmt"
23
24	"github.com/vmware/govmomi/govc/cli"
25	"github.com/vmware/govmomi/govc/flags"
26)
27
28type add struct {
29	*flags.VirtualMachineFlag
30}
31
32func init() {
33	cli.Register("device.serial.add", &add{})
34}
35
36func (cmd *add) Register(ctx context.Context, f *flag.FlagSet) {
37	cmd.VirtualMachineFlag, ctx = flags.NewVirtualMachineFlag(ctx)
38	cmd.VirtualMachineFlag.Register(ctx, f)
39}
40
41func (cmd *add) Description() string {
42	return `Add serial port to VM.
43
44Examples:
45  govc device.serial.add -vm $vm
46  govc device.info -vm $vm serialport-*`
47}
48
49func (cmd *add) Process(ctx context.Context) error {
50	if err := cmd.VirtualMachineFlag.Process(ctx); err != nil {
51		return err
52	}
53	return nil
54}
55
56func (cmd *add) Run(ctx context.Context, f *flag.FlagSet) error {
57	vm, err := cmd.VirtualMachine()
58	if err != nil {
59		return err
60	}
61
62	if vm == nil {
63		return flag.ErrHelp
64	}
65
66	devices, err := vm.Device(ctx)
67	if err != nil {
68		return err
69	}
70
71	d, err := devices.CreateSerialPort()
72	if err != nil {
73		return err
74	}
75
76	err = vm.AddDevice(ctx, d)
77	if err != nil {
78		return err
79	}
80
81	// output name of device we just created
82	devices, err = vm.Device(ctx)
83	if err != nil {
84		return err
85	}
86
87	devices = devices.SelectByType(d)
88
89	name := devices.Name(devices[len(devices)-1])
90
91	fmt.Println(name)
92
93	return nil
94}
95