1package mutator
2
3import (
4	"errors"
5	"fmt"
6
7	"github.com/sensu/sensu-go/cli"
8	"github.com/spf13/cobra"
9)
10
11// UpdateCommand defines the 'mutator update' subcommand
12func UpdateCommand(cli *cli.SensuCli) *cobra.Command {
13	cmd := &cobra.Command{
14		Use:          "update [NAME]",
15		Short:        "update mutators",
16		SilenceUsage: false,
17		RunE: func(cmd *cobra.Command, args []string) error {
18			// Print out usage if we do not receive one argument
19			if len(args) != 1 {
20				_ = cmd.Help()
21				return errors.New("invalid argument(s) received")
22			}
23
24			// Fetch the requested mutator from the API
25			name := args[0]
26			mutator, err := cli.Client.FetchMutator(name)
27			if err != nil {
28				return err
29			}
30
31			// Administer questionnaire
32			opts := newMutatorOpts()
33			opts.withMutator(mutator)
34			if err := opts.administerQuestionnaire(true); err != nil {
35				return err
36			}
37
38			// Apply given arguments to mutator
39			opts.Copy(mutator)
40
41			if err := mutator.Validate(); err != nil {
42				return err
43			}
44
45			if err := cli.Client.UpdateMutator(mutator); err != nil {
46				return err
47			}
48
49			fmt.Fprintln(cmd.OutOrStdout(), "Updated")
50			return nil
51		},
52	}
53
54	return cmd
55}
56