package commands

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

	"github.com/contiamo/dev/cli/config"
	"github.com/pkg/errors"
	"github.com/sirupsen/logrus"
	"github.com/spf13/cobra"
	"github.com/spf13/viper"
)

func init() {
	initCmd.Flags().BoolP("skip-clone", "s", false, "skip cloning the local dev repo, simply setup the config")
}

var initCmd = &cobra.Command{
	Use:     "init [absPathToCloneTo]",
	Short:   "create a localdev environment and configure the cli settings",
	Example: initExamples,
	Args:    cobra.RangeArgs(0, 1),
	RunE: func(cmd *cobra.Command, args []string) error {
		target := viper.GetString("localdevRoot")
		if len(args) > 0 {
			target = args[0]
		}

		target = os.ExpandEnv(target)
		viper.Set("localdevRoot", target)

		skipClone, err := cmd.Flags().GetBool("skip-clone")
		if err != nil {
			return err
		}

		if !skipClone {
			_, err := os.Stat(target)
			if !os.IsNotExist(err) {
				if err != nil {
					return err
				}
				return fmt.Errorf("target location may already exist: %q", target)
			}

			repoURL := "git@github.com:contiamo/dev.git"
			clone := exec.CommandContext(
				cmd.Context(),
				"git",
				"clone", repoURL, target,
			)
			clone.Stderr = cmd.OutOrStderr()
			clone.Stdout = cmd.OutOrStdout()
			clone.Env = os.Environ()
			err = clone.Run()
			if err != nil {
				return err
			}
		} else {
			logrus.Debug("skipping localdev clone")
		}

		write := viper.WriteConfig
		path := viper.ConfigFileUsed()
		if path == "" {
			write = viper.SafeWriteConfig
			path = config.DefaultConfigFile()
		}

		logrus.Debugf("writing config file to: %q", path)

		err = write()
		return errors.Wrap(err, "can not save config")
	},
}
