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 flags
18
19import (
20	"context"
21	"flag"
22	"fmt"
23	"os"
24
25	"github.com/vmware/govmomi/object"
26)
27
28type ResourcePoolFlag struct {
29	common
30
31	*DatacenterFlag
32
33	name string
34	pool *object.ResourcePool
35}
36
37var resourcePoolFlagKey = flagKey("resourcePool")
38
39func NewResourcePoolFlag(ctx context.Context) (*ResourcePoolFlag, context.Context) {
40	if v := ctx.Value(resourcePoolFlagKey); v != nil {
41		return v.(*ResourcePoolFlag), ctx
42	}
43
44	v := &ResourcePoolFlag{}
45	v.DatacenterFlag, ctx = NewDatacenterFlag(ctx)
46	ctx = context.WithValue(ctx, resourcePoolFlagKey, v)
47	return v, ctx
48}
49
50func (flag *ResourcePoolFlag) Register(ctx context.Context, f *flag.FlagSet) {
51	flag.RegisterOnce(func() {
52		flag.DatacenterFlag.Register(ctx, f)
53
54		env := "GOVC_RESOURCE_POOL"
55		value := os.Getenv(env)
56		usage := fmt.Sprintf("Resource pool [%s]", env)
57		f.StringVar(&flag.name, "pool", value, usage)
58	})
59}
60
61func (flag *ResourcePoolFlag) Process(ctx context.Context) error {
62	return flag.ProcessOnce(func() error {
63		if err := flag.DatacenterFlag.Process(ctx); err != nil {
64			return err
65		}
66		return nil
67	})
68}
69
70func (flag *ResourcePoolFlag) ResourcePool() (*object.ResourcePool, error) {
71	if flag.pool != nil {
72		return flag.pool, nil
73	}
74
75	finder, err := flag.Finder()
76	if err != nil {
77		return nil, err
78	}
79
80	if flag.pool, err = finder.ResourcePoolOrDefault(context.TODO(), flag.name); err != nil {
81		return nil, err
82	}
83
84	return flag.pool, nil
85}
86
87func (flag *ResourcePoolFlag) ResourcePoolIfSpecified() (*object.ResourcePool, error) {
88	if flag.name == "" {
89		return nil, nil
90	}
91	return flag.ResourcePool()
92}
93