package utils

import (
	"fmt"
	"os"
	"os/exec"

	"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/store"
)

var ()

var icemanCmd = &cobra.Command{
	Use:   "iceman [cluster] [iceman args]",
	Short: "Execute an iceman command against a local repository",
	Long:  "When `buddy auth` is entered, the user will be prompted for username and password, then the credential pair will be used to authorize the RDS Buddy application to create repositories and check in code.",
	RunE: func(command *cobra.Command, args []string) error {
		if icemanHelp && len(args) < 2 {
			cmd := exec.Command("iceman", "--help")
			cmd.Stderr = os.Stderr
			cmd.Stdin = os.Stdin
			cmd.Stdout = os.Stdout
			return cmd.Run()
		}

		if len(args) < 2 {
			return command.Usage()
		}

		clusterName := args[0]
		icemanArgs := args[1:]

		rdsInstance, err := data.RootData.LocateDataStore(false)
		if err != nil {
			return err
		}

		db, err := store.OpenDbConn(rdsInstance, data.RootData.SandstormClient())
		if err != nil {
			return err
		}

		data.RootData.ConfigFile().Cluster, err = store.GetClusters(db)
		if err != nil {
			return err
		}

		foundCluster := data.RootData.ConfigFile().GetCluster(clusterName)
		if foundCluster == nil {
			return fmt.Errorf("There is no cluster named %s.  Did you forget to tag your instances?", clusterName)
		}

		_, err = os.Stat(foundCluster.RepoFolder())
		if err != nil {
			if os.IsNotExist(err) {
				return fmt.Errorf("There was no iceman repository at %s - you may need to run `buddy setup`", foundCluster.RepoFolder())
			}
			return err
		}

		var allArgs []string

		if icemanHelp {
			allArgs = []string{"--help"}
		} else {
			allArgs = []string{"-e", foundCluster.Environment}

			if len(foundCluster.Schema) > 0 {
				allArgs = append(allArgs, "-s", foundCluster.Schema)
			}
		}
		allArgs = append(icemanArgs, allArgs...)
		fmt.Println(allArgs)
		cmd := exec.Command("iceman", allArgs...)
		cmd.Dir = foundCluster.RepoFolder()
		cmd.Stderr = os.Stderr
		cmd.Stdin = os.Stdin
		cmd.Stdout = os.Stdout
		return cmd.Run()
	},
}

var icemanHelp bool

func init() {
	icemanCmd.Flags().BoolVarP(&icemanHelp, "iceman-help", "", false, "View iceman help")
	setup.RootCmd.AddCommand(icemanCmd)
}
