package configuration

import (
	"fmt"

	"code.justin.tv/d8a/buddy/cmd/buddy-cli/data"
	"code.justin.tv/d8a/buddy/lib/clusters/clusterdb"
	"code.justin.tv/d8a/buddy/lib/sandstorm"
	"code.justin.tv/d8a/buddy/lib/store"
	"code.justin.tv/d8a/buddy/lib/terminal"
	"github.com/fatih/color"
	"github.com/pkg/errors"
	"github.com/spf13/cobra"
)

var removeUser = &cobra.Command{
	Use:   "remove-user [cluster] [username]",
	Short: "Remove a user from a cluster.",
	Long:  "Remove a user from a cluster.  Can't remove a user that is part of a live role pair.",
	RunE: func(command *cobra.Command, args []string) error {
		if len(data.ConfigureData.Args()) != 1 {
			return command.Usage()
		}

		username := data.ConfigureData.Args()[0]
		foundCluster := data.ConfigureData.FoundCluster()

		if username == foundCluster.SuperUser {
			return fmt.Errorf("cannot remove '%s' because it is the superuser of %s", username, foundCluster.Name)
		}

		foundUser := foundCluster.GetUser(username)
		if foundUser == nil {
			return fmt.Errorf("could not find user '%s' in cluster %s", username, foundCluster.Name)
		}

		//Don't allow users in active pairs to be deleted- wipe the pair first
		if foundUser.RolePair != nil {
			return fmt.Errorf("user '%s' is a member of role pair '%s' - remove it with configure remove-role-pair first", foundUser.Name, foundUser.RolePair.Name)
		}

		clusterDb, err := clusterdb.OpenDbConn(foundCluster, data.ConfigureData.SandstormClient(), username)
		if err != nil {
			return errors.Wrap(err, fmt.Sprintf("could not connect to cluster %s", foundCluster.Name))
		}

		userMap, err := clusterDb.ClusterUsers()
		if err != nil {
			return errors.Wrap(err, fmt.Sprintf("could not retrieve users for cluster %s", foundCluster.Name))
		}

		canlogin, ok := userMap[username]
		if ok && canlogin && clusterDb.CanLockUsers() {
			disableLogin, err := terminal.AskForConfirmation(fmt.Sprintf("User %s is still accepting logins.  Set it to NOLOGIN?", username))
			if err != nil {
				return err
			}

			if disableLogin {
				err = clusterDb.SetUserLogin(username, false)
				if err != nil {
					return errors.Wrap(err, fmt.Sprintf("could not set %s to NOLOGIN", username))
				}
			}
		}

		err = store.DeleteUser(data.ConfigureData.StoreDB(), foundUser)
		if err != nil {
			return errors.Wrap(err, fmt.Sprintf("could not remove %s from the buddy store", username))
		}

		err = sandstorm.RemoveTemplate(foundCluster, username)
		if err != nil {
			return errors.Wrap(err, "could not remove sandstorm templates from disk")
		}

		_, err = sandstorm.WritePasswordFiles(data.ConfigureData.ConfigFile().Cluster)
		if err != nil {
			color.Red("%v", err)
		}

		err = sandstorm.Reload()
		if err != nil {
			return errors.Wrap(err, "could not issue SIGHUP to sandstorm agent")
		}

		return nil
	},
}

func init() {
	ConfigureCmd.AddCommand(removeUser)
}
