1package entity
2
3import (
4	"errors"
5	"fmt"
6
7	"github.com/sensu/sensu-go/cli"
8	"github.com/spf13/cobra"
9)
10
11// UpdateCommand adds command that allows user to create new checks
12func UpdateCommand(cli *cli.SensuCli) *cobra.Command {
13	cmd := &cobra.Command{
14		Use:          "update [ID]",
15		Short:        "update entity",
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 specified entity from API
25			id := args[0]
26			entity, err := cli.Client.FetchEntity(id)
27			if err != nil {
28				return err
29			}
30
31			// Administer questionnaire
32			opts := newEntityOpts()
33			opts.withEntity(entity)
34			if err := opts.administerQuestionnaire(); err != nil {
35				return err
36			}
37
38			// Apply given arguments to check
39			opts.copy(entity)
40
41			if err := entity.Validate(); err != nil {
42				return err
43			}
44
45			if err := cli.Client.UpdateEntity(entity); err != nil {
46				return err
47			}
48
49			fmt.Fprintln(cmd.OutOrStdout(), "Updated")
50			return nil
51		},
52	}
53
54	return cmd
55}
56