package reset

import (
	dcuTracker "dcu-container-toolkit/internal/dcu-tracker"
	"fmt"
	"os/user"

	"dcu-container-toolkit/internal/logger"

	"github.com/urfave/cli/v2"
)

type command struct {
	logger logger.Interface
}

func NewCommand(logger logger.Interface) *cli.Command {
	c := command{
		logger: logger,
	}
	return c.build()
}

func (m command) build() *cli.Command {
	dcuTrackerResetCmd := cli.Command{
		Name:      "reset",
		Usage:     "Reset the DCU Tracker",
		UsageText: "dcu-ctk dcu-tracker reset [options]",
		Before: func(c *cli.Context) error {
			return validateGenOptions(c)
		},
		Action: func(c *cli.Context) error {
			return performAction(c)
		},
	}

	return &dcuTrackerResetCmd
}

func validateGenOptions(c *cli.Context) error {
	curUser, err := user.Current()
	if err != nil || curUser.Uid != "0" {
		return fmt.Errorf("Permission denied: Not running as root")
	}

	return nil
}

func performAction(c *cli.Context) error {
	dcuTracker, err := dcuTracker.New()
	if err != nil {
		return fmt.Errorf("Failed to create DCU tracker, Error: %v", err)
	}

	err = dcuTracker.Reset()
	if err != nil {
		return fmt.Errorf("Failed to Reset DCU Tracker, Error: %v", err)
	}

	return nil
}

