package control

import (
	"os"
	
	"github.com/spf13/cobra"
	"gitea.sunhpc.com/kelvin/sunhpc/internal/app/control/clean"
	"gitea.sunhpc.com/kelvin/sunhpc/internal/app/control/configure"

	sunhpcconf "gitea.sunhpc.com/kelvin/sunhpc/internal/pkg/config"
	"gitea.sunhpc.com/kelvin/sunhpc/internal/pkg/help"
	"gitea.sunhpc.com/kelvin/sunhpc/internal/pkg/splog"
)

var (
	rootCmd = &cobra.Command{
		DisableFlagsInUseLine: true,
		Use:     "sunhpc control COMMAND [options] [FLAGS]",
		Short:   "Sunhpc Control",
		Long:    `Control interface to the SunHPC Cluster Provisioning System.`,
		PersistentPreRunE: rootPersistentPreRunE,
		SilenceUsage: 	true,
		SilenceErrors: 	true,
		Args: 			cobra.NoArgs,
	}
	verboseArg		bool
	DebugFlag		bool
	LogLevel		int
	SunhpcConfArg	string
	AllowEmptyConf	bool
)

func init() {
	//rootCmd.CompletionOptions.HiddenDefaultCmd = true
	rootCmd.PersistentFlags().BoolVarP(&verboseArg, "verbose", "v", false, "verbose output")
	rootCmd.PersistentFlags().BoolVarP(&DebugFlag, "debug", "d", false, "debug output")
	rootCmd.PersistentFlags().IntVar(&LogLevel, "loglevel", splog.INFO, "Set log level to given string")
	_ = rootCmd.PersistentFlags().MarkHidden("loglevel")
	rootCmd.PersistentFlags().StringVar(&SunhpcConfArg, "sunhpcconf", "", "Set the sunhpc configuration file")
	rootCmd.PersistentFlags().BoolVar(&AllowEmptyConf, "emptyconf", false, "Allow empty configuration")
	_ = rootCmd.PersistentFlags().MarkHidden("emptyconf")

	rootCmd.SetUsageTemplate(help.UsageTemplate)
	rootCmd.SetHelpTemplate(help.HelpTemplate)

	rootCmd.AddCommand(clean.GetCommand())
	rootCmd.AddCommand(configure.GetCommand())
}

func GetRootCommand() *cobra.Command {
	return rootCmd
}

func rootPersistentPreRunE(cmd *cobra.Command, args []string) (err error) {
	if DebugFlag {
		splog.SetLogLevel(splog.DEBUG)
	} else if verboseArg {
		splog.SetLogLevel(splog.VERBOSE)
	} else {
		splog.SetLogLevel(splog.INFO)
	}
	if LogLevel != splog.INFO {
		splog.SetLogLevel(LogLevel)
	}

	if SunhpcConfArg != "" {
		sunhpcconf.ConfigFile = SunhpcConfArg
	} else if os.Getenv("SUNHPC_CONF") != "" {
		sunhpcconf.ConfigFile = os.Getenv("SUNHPC_CONF")
	}

	conf := sunhpcconf.Get()
	if !AllowEmptyConf && !conf.InitializedFromFile() {
		if err = conf.Read(sunhpcconf.ConfigFile, true); err != nil {
			splog.Error("error reading configuration file: %s", err)
			return
		}
	}
	return
}
