// generic root command
package main

import (
	"errors"
	"github.com/fatih/color"
	"github.com/spf13/cobra"
	"os"
)

var (
	path   string
	env    string
	schema string
	red    *color.Color
	yellow *color.Color
	green  *color.Color
)

// set up flags and colors
func init() {
	RootCmd.PersistentFlags().StringVarP(&path, "path", "p", "iceman", "directory containing DB information")
	RootCmd.PersistentFlags().StringVarP(&env, "env", "e", "", "which DB environment to use (references dbconf.yaml)")
	RootCmd.PersistentFlags().StringVarP(&schema, "schema", "s", "", "which postgres schema to migrate")

	red = color.New(color.FgRed)
	yellow = color.New(color.FgYellow)
	green = color.New(color.FgGreen)
}

var RootCmd = &cobra.Command{
	Use:           "iceman",
	SilenceErrors: true,
	SilenceUsage:  true,
	Short:         "data migrations tool for postgres",
	Long: `Use the appropriate subcommands to create, apply, or roll back data migrations. There is also support for bulk operations. 
	Complete documentation can be found at https://git-aws.internal.justin.tv/d8a/iceman`,
	PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
		if env == "" {
			return errors.New("environment must be defined and reflected in dbconf.yaml, use flag env, e.g. development, staging, or production")
		}

		return nil
	},
}

// Execute adds all child commands to the root command sets flags appropriately.
// This is called by main.main(). It only needs to happen once to the rootCmd.
func Execute() {
	if err := RootCmd.Execute(); err != nil {
		red.Println(err)
		os.Exit(-1)
	}
}
