package commands

import (
	"os"
	"os/exec"
	"path/filepath"

	"github.com/sirupsen/logrus"
	"github.com/spf13/cobra"

	"github.com/contiamo/dev/cli/config"
	"github.com/contiamo/dev/cli/tar"
)

const dumpPath = "config/dumps"

func init() {
	serviceFlags(restoreCmd.Flags())
	restoreCmd.Flags().StringP("filename", "f", "localdev.snapshot", "snapshot filename in the localdev environment.")
}

var restoreCmd = &cobra.Command{
	Use:   "restore",
	Short: "loads the dev environment db snapshot",
	Example: `
	localdev restore`,
	RunE: func(cmd *cobra.Command, args []string) error {
		source, err := cmd.Flags().GetString("filename")
		if err != nil {
			return err
		}

		withIngester, err := cmd.Flags().GetBool("ingester")
		if err != nil {
			return err
		}

		withPantheonRedir, err := cmd.Flags().GetBool("pantheon")
		if err != nil {
			return err
		}

		snapshotPath := filepath.Join(config.LocaldevRoot(), source)
		logrus.Debugln("loading snapshot from:", snapshotPath)
		snapshot, err := os.Open(snapshotPath)
		if err != nil {
			return err
		}

		dst := filepath.Join(config.LocaldevRoot(), dumpPath)
		logrus.Debugln("extracting snapshot to:", dst)

		err = os.MkdirAll(dumpPath, 0755)
		if err != nil {
			return err
		}

		err = tar.Extract(dst, snapshot)
		if err != nil {
			return err
		}

		clean := exec.CommandContext(
			cmd.Context(),
			"docker-compose",
			"down",
			"--remove-orphans",
			"--volumes",
		)
		clean.Dir = config.LocaldevRoot()
		clean.Stderr = cmd.OutOrStderr()
		clean.Stdout = cmd.OutOrStdout()
		clean.Env = os.Environ()

		err = clean.Run()
		if err != nil {
			return err
		}

		err = startLocaldev(cmd, withIngester, withPantheonRedir, nil)
		if err != nil {
			return err
		}

		return printStartMessage(cmd.OutOrStdout())
	},
}
