// apply bulk
package main

import (
	"fmt"
	"strconv"
	"syscall"

	"code.justin.tv/d8a/iceman/lib/bulk"
	"code.justin.tv/d8a/iceman/lib/dbconf"
	"code.justin.tv/d8a/iceman/lib/queries"

	"github.com/spf13/cobra"
	"golang.org/x/crypto/ssh/terminal"
)

// createCmd represents the create command
var bulkCmd = &cobra.Command{
	Use:   "bulk [operation_name]",
	Short: "execute a bulk operation",
	Long:  "This will run the specified bulk operation.",
	RunE: func(cmd *cobra.Command, args []string) error {
		conf, err := dbconf.NewDBConf(path, env, schema, "bulk")
		if err != nil {
			return err
		}

		params, err := getOverrideParams()
		if err != nil {
			return err
		}

		err = conf.SubstituteDBParams(params)
		if err != nil {
			return err
		}

		db, err := dbconf.OpenDBFromDBConf(conf)
		if err != nil {
			return err
		}
		defer queries.TryClose(db)

		if err := bulk.RunBulk(db, conf.DriverQueries, conf.Dir); err != nil {
			return err
		}
		return nil
	},
}

var (
	connHost string
	connPort int
	connUser string
	connDb   string
	connPw   bool
)

func init() {
	bulkCmd.PersistentFlags().StringVarP(&connHost, "host", "", "", "host to use instead of the one specified in dbConf.yaml")
	bulkCmd.PersistentFlags().IntVarP(&connPort, "port", "", 0, "port to use instead of the one in dbConf.yaml")
	bulkCmd.PersistentFlags().StringVarP(&connUser, "user", "U", "", "username to use instead of the one specified in dbConf.yaml")
	bulkCmd.PersistentFlags().StringVarP(&connDb, "dbname", "d", "", "database name to use instead of the one specified in dbConf.yaml")
	bulkCmd.PersistentFlags().BoolVarP(&connPw, "password-prompt", "W", false, "whether to prompt for a password to use instead of the one specified in dbConf.yaml")
	RootCmd.AddCommand(bulkCmd)
}

func getOverrideParams() (map[string]string, error) {
	params := make(map[string]string)
	if connHost != "" {
		params["host"] = connHost
	}

	if connPort != 0 {
		params["port"] = strconv.Itoa(connPort)
	}

	if connUser != "" {
		params["user"] = connUser
	}

	if connDb != "" {
		params["dbname"] = connDb
	}

	if connPw {
		fmt.Print("Enter database password: ")
		passwordBytes, err := terminal.ReadPassword(syscall.Stdin)
		fmt.Println()

		if err != nil {
			return params, err
		}

		params["password"] = string(passwordBytes)
	}

	return params, nil
}
