package utils

import (
	"fmt"

	"github.com/spf13/cobra"
	"code.justin.tv/d8a/buddy/cmd/buddy-cli/data"
	"code.justin.tv/d8a/buddy/cmd/buddy-cli/setup"
	"code.justin.tv/d8a/buddy/lib/zenyatta"
)

var cmdOptions = "[up|terminate|refresh]"
var configKey = "etc/zenyatta"

var workersCmd = &cobra.Command{
	Use:   fmt.Sprintf("workers %s", cmdOptions),
	Short: "brings workers up, terminates, or terminates then brings them back up with refresh",
	Long:  fmt.Sprintf("`buddy workers %s` will start a new worker(s), terminate existing worker(s), or terminate and then bring up new worker(s) with refresh", cmdOptions),
	RunE: func(command *cobra.Command, args []string) error {
		configFile := data.RootData.ConfigFile()

		if len(args) < 1 {
			return command.Usage()
		}
		todo := args[0]

		switch todo {
			case "up":
				fmt.Println("attempting to start worker")
				return zenyatta.StartZenyattaWorker(configFile.SandstormTeam, data.RootData.Region(), configFile.Environment, configKey)
			case "terminate":
				fmt.Println("attempting to terminate worker")
				err := zenyatta.TerminateZenyattaWorker(data.RootData.Ec2Client(), fmt.Sprintf("%s-zenyatta-worker", configFile.SandstormTeam))
				return err
			case "refresh":
				fmt.Println("attempting to refresh workers")
				fmt.Println("terminating..")
				err := zenyatta.TerminateZenyattaWorker(data.RootData.Ec2Client(), fmt.Sprintf("%s-zenyatta-worker", configFile.SandstormTeam))
				if err != nil {
					fmt.Println(fmt.Sprintf("error terminating: %s", err.Error()))
					return err
				}
				fmt.Println("starting new worker..")
				err = zenyatta.StartZenyattaWorker(configFile.SandstormTeam, data.RootData.Region(), configFile.Environment, configKey)
				return err
			default:
				fmt.Println(fmt.Sprintf("%s is not a valid option. Please pick one from %s", todo, cmdOptions))
				return nil
		}
	},
}

func init() {
	setup.RootCmd.AddCommand(workersCmd)
}
