1package hook
2
3import (
4	"fmt"
5	"strconv"
6
7	"github.com/AlecAivazis/survey"
8	"github.com/sensu/sensu-go/cli/commands/helpers"
9	"github.com/sensu/sensu-go/types"
10	"github.com/spf13/pflag"
11)
12
13const (
14	timeoutDefault = "60"
15)
16
17const (
18	stdinDefault = "false"
19)
20
21type hookOpts struct {
22	Name      string `survey:"name"`
23	Command   string `survey:"command"`
24	Timeout   string `survey:"timeout"`
25	Stdin     string `survey:"stdin"`
26	Env       string
27	Namespace string
28}
29
30func newHookOpts() *hookOpts {
31	opts := hookOpts{}
32	opts.Timeout = timeoutDefault
33	opts.Stdin = stdinDefault
34	return &opts
35}
36
37func (opts *hookOpts) withHook(hook *types.HookConfig) {
38	opts.Name = hook.Name
39	opts.Namespace = hook.Namespace
40	opts.Command = hook.Command
41	opts.Timeout = strconv.Itoa(int(hook.Timeout))
42	opts.Stdin = strconv.FormatBool(hook.Stdin)
43}
44
45func (opts *hookOpts) withFlags(flags *pflag.FlagSet) {
46	opts.Command, _ = flags.GetString("command")
47	opts.Timeout, _ = flags.GetString("timeout")
48	stdinBool, _ := flags.GetBool("stdin")
49	opts.Stdin = strconv.FormatBool(stdinBool)
50
51	if namespace := helpers.GetChangedStringValueFlag("namespace", flags); namespace != "" {
52		opts.Namespace = namespace
53	}
54}
55
56func (opts *hookOpts) administerQuestionnaire(editing bool) error {
57	var qs = []*survey.Question{}
58
59	if !editing {
60		qs = append(qs, []*survey.Question{
61			{
62				Name: "name",
63				Prompt: &survey.Input{
64					Message: "Hook Name:",
65					Default: opts.Name,
66				},
67				Validate: survey.Required,
68			},
69			{
70				Name: "namespace",
71				Prompt: &survey.Input{
72					Message: "Namespace:",
73					Default: opts.Namespace,
74				},
75				Validate: survey.Required,
76			},
77		}...)
78	}
79
80	qs = append(qs, []*survey.Question{
81		{
82			Name: "command",
83			Prompt: &survey.Input{
84				Message: "Command:",
85				Default: opts.Command,
86			},
87			Validate: survey.Required,
88		},
89		{
90			Name: "timeout",
91			Prompt: &survey.Input{
92				Message: "Timeout:",
93				Default: opts.Timeout,
94			},
95		},
96		{
97			Name: "stdin",
98			Prompt: &survey.Input{
99				Message: "Stdin:",
100				Help:    "If stdin is enabled for the hook. Value must be true or false.",
101				Default: opts.Stdin,
102			},
103			Validate: func(val interface{}) error {
104				if str := val.(string); str != "false" && str != "true" {
105					return fmt.Errorf("Please enter either true or false")
106				}
107				return nil
108			},
109		},
110	}...)
111
112	return survey.Ask(qs, opts)
113}
114
115func (opts *hookOpts) Copy(hook *types.HookConfig) {
116	timeout, _ := strconv.ParseUint(opts.Timeout, 10, 32)
117	stdin, _ := strconv.ParseBool(opts.Stdin)
118
119	hook.Name = opts.Name
120	hook.Namespace = opts.Namespace
121	hook.Timeout = uint32(timeout)
122	hook.Command = opts.Command
123	hook.Stdin = stdin
124}
125