1/*
2Copyright (c) 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 role
18
19import (
20	"context"
21	"flag"
22
23	"github.com/vmware/govmomi/govc/cli"
24	"github.com/vmware/govmomi/govc/permissions"
25)
26
27type update struct {
28	*permissions.PermissionFlag
29
30	name   string
31	remove bool
32	add    bool
33}
34
35func init() {
36	cli.Register("role.update", &update{})
37}
38
39func (cmd *update) Register(ctx context.Context, f *flag.FlagSet) {
40	cmd.PermissionFlag, ctx = permissions.NewPermissionFlag(ctx)
41	cmd.PermissionFlag.Register(ctx, f)
42
43	f.StringVar(&cmd.name, "name", "", "Change role name")
44	f.BoolVar(&cmd.remove, "r", false, "Remove given PRIVILEGE(s)")
45	f.BoolVar(&cmd.add, "a", false, "Add given PRIVILEGE(s)")
46}
47
48func (cmd *update) Process(ctx context.Context) error {
49	if err := cmd.PermissionFlag.Process(ctx); err != nil {
50		return err
51	}
52	return nil
53}
54
55func (cmd *update) Usage() string {
56	return "NAME [PRIVILEGE]..."
57}
58
59func (cmd *update) Description() string {
60	return `Update authorization role.
61
62Set, Add or Remove role PRIVILEGE(s).
63
64Examples:
65  govc role.update MyRole $(govc role.ls Admin | grep VirtualMachine.)
66  govc role.update -r MyRole $(govc role.ls Admin | grep VirtualMachine.GuestOperations.)
67  govc role.update -a MyRole $(govc role.ls Admin | grep Datastore.)
68  govc role.update -name RockNRole MyRole`
69}
70
71func (cmd *update) Run(ctx context.Context, f *flag.FlagSet) error {
72	if f.NArg() == 0 {
73		return flag.ErrHelp
74	}
75
76	m, err := cmd.Manager(ctx)
77	if err != nil {
78		return err
79	}
80
81	role, err := cmd.Role(f.Arg(0))
82	if err != nil {
83		return err
84	}
85
86	ids := role.Privilege
87	args := f.Args()[1:]
88
89	if cmd.add {
90		ids = append(ids, args...)
91	} else if cmd.remove {
92		ids = nil
93		rm := make(map[string]bool, len(args))
94		for _, arg := range args {
95			rm[arg] = true
96		}
97
98		for _, id := range role.Privilege {
99			if !rm[id] {
100				ids = append(ids, id)
101			}
102		}
103	} else if len(args) != 0 {
104		ids = args
105	}
106
107	if cmd.name == "" {
108		cmd.name = role.Name
109	}
110
111	return m.UpdateRole(ctx, role.RoleId, cmd.name, ids)
112}
113