package utils

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

	"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 psqlCmd = &cobra.Command{
	Use:   "psql [cluster] [optional: user]",
	Short: "Launch psql to connect to the specified cluster",
	Long:  "Is equivalent to running psql, but the connection information and password are retrieved seamlessly.  If user is not specified, the superuser for the cluster is used.",
	RunE: func(command *cobra.Command, args []string) error {
		if len(args) < 1 || len(args) > 2 {
			return command.Usage()
		}

		clusterName := args[0]

		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)
		}

		userName := foundCluster.SuperUser
		if len(args) > 1 {
			userName = args[1]
		}

		password, err := data.RootData.SandstormClient().GetUserPassword(foundCluster, userName)
		if err != nil {
			return err
		}

		env := os.Environ()
		env = append(env, fmt.Sprintf("PGPASSWORD=%s", password))

		cmd := exec.Command("psql", "-h", foundCluster.Host, "-p", strconv.Itoa(foundCluster.Port), "-d", foundCluster.Database, "-U", userName, "-w")
		cmd.Stderr = os.Stderr
		cmd.Stdin = os.Stdin
		cmd.Stdout = os.Stdout
		cmd.Env = env

		return cmd.Run()
	},
}

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