1/*
2Copyright 2018 The Doctl Authors All rights reserved.
3Licensed under the Apache License, Version 2.0 (the "License");
4you may not use this file except in compliance with the License.
5You may obtain a copy of the License at
6    http://www.apache.org/licenses/LICENSE-2.0
7Unless required by applicable law or agreed to in writing, software
8distributed under the License is distributed on an "AS IS" BASIS,
9WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10See the License for the specific language governing permissions and
11limitations under the License.
12*/
13
14package pluginhost
15
16import (
17	"fmt"
18	"log"
19	"net/rpc"
20	"net/rpc/jsonrpc"
21	"os"
22
23	"github.com/digitalocean/doctl"
24	"github.com/natefinch/pie"
25	"github.com/spf13/viper"
26)
27
28// Host is an object consumers can retrieve doit information from.
29type Host struct {
30	client *rpc.Client
31}
32
33// NewHost builds an instance of Host.
34func NewHost(pluginPath string) (*Host, error) {
35	client, err := pie.StartProviderCodec(jsonrpc.NewClientCodec, os.Stderr, pluginPath)
36	if err != nil {
37		return nil, err
38	}
39
40	return &Host{
41		client: client,
42	}, nil
43}
44
45// Call a method on the plugin.
46func (h *Host) Call(method string, args ...string) (string, error) {
47	opts := &CallOptions{
48		AccessToken: viper.GetString(doctl.ArgAccessToken),
49		Args:        args,
50	}
51
52	var result string
53	err := h.client.Call(method, opts, &result)
54	if err != nil {
55		debug(err.Error())
56		return "", fmt.Errorf("unable to run plugin action %s", method)
57	}
58
59	return result, nil
60}
61
62func debug(msg string) {
63	//if viper.GetBool("verbose") {
64	log.Println(msg)
65	//}
66}
67
68// CallOptions are options to a plugin call. This is exported so go based plugins
69// can use the type.
70type CallOptions struct {
71	AccessToken string
72	Args        []string
73}
74