package cmd

import (
	"errors"
	"fmt"
	"os"
	"strings"

	"github.com/spf13/cobra"
)

// command line flags
var (
	rootConfig         string
	namespace          string
	baseKubeconfig     string
	infraAPIKubeconfig string

	enableCMControllers        bool
	enableNetworkControllers   bool
	enableDPControllers        bool
	enableK8sVersionController bool
	enableUOController         bool
	enabledControllers         []string

	pprofActive          bool
	enableLeaderElection bool
	probeAddr            string
	metricsAddr          string

	// command line flags that override config file
	// These make it simpler to deploy new region
	region                  string
	zones                   []string
	assumeRoleName          string
	readonlyAssumeRoleName  string
	awsClusterServerRoleARN string
	gcpClusterServerSAName  string
	overrideRegistry        string
	overrideHelperImage     string

	DryRun bool
)

func init() {
	rootCmd.PersistentFlags().StringVar(&rootConfig, "root-config", "", "The path to the root config.")
	rootCmd.PersistentFlags().StringVar(&namespace, "namespace", "", "The namespace for storing EKSConnection configmap and resources.")
	rootCmd.PersistentFlags().StringVar(&baseKubeconfig, "base-kubeconfig", "", "The kubeconfig for deploying workloads such as frps services.")
	rootCmd.PersistentFlags().StringVar(&infraAPIKubeconfig, "infra-kubeconfig", "/.kube/config", "The kubeconfig for infra-api")
	rootCmd.PersistentFlags().BoolVar(&DryRun, "dryrun", false, "Use dryrun mode")

	rootCmd.PersistentFlags().StringSliceVar(&enabledControllers, "enabled-controllers", nil, fmt.Sprintf("A comma separated list of enabled controllers. Available controllers: %s.", strings.Join(availableControllers[:], ",")))
	rootCmd.PersistentFlags().BoolVar(&enableCMControllers, "enable-cm-controllers", true, "Enable CM controllers for controller manager.")
	rootCmd.PersistentFlags().BoolVar(&enableNetworkControllers, "enable-network-controllers", true, "Enable network controllers for controller manager.")
	rootCmd.PersistentFlags().BoolVar(&enableDPControllers, "enable-dp-controllers", false, "Enable DP controllers for controller manager.")
	rootCmd.PersistentFlags().BoolVar(&enableK8sVersionController, "enable-k8s-version-controller", false, "Enable k8s version controllers for upgrading k8s only.")
	rootCmd.PersistentFlags().BoolVar(&enableUOController, "enable-uo-controller", false, "Enable the UpgradeOperation controller in 3-layer arch.")

	rootCmd.PersistentFlags().StringVar(&probeAddr, "health-probe-bind-address", ":8081", "The address the probe endpoint binds to.")
	rootCmd.PersistentFlags().BoolVar(&pprofActive, "pprof", true, "Enable pprof endpoint")
	rootCmd.PersistentFlags().BoolVar(&enableLeaderElection, "leader-elect", false, "Enable leader election for controller manager. Enabling this will ensure there is only one active controller manager")
	rootCmd.PersistentFlags().StringVar(&metricsAddr, "metrics-bind-address", ":8080", "The address the metric endpoint binds to.")

	rootCmd.PersistentFlags().StringVar(&region, "region", "", "The region cluster-controller deployed")
	rootCmd.PersistentFlags().StringSliceVar(&zones, "zones", nil, "The available zones separated by comma for the region")
	rootCmd.PersistentFlags().StringVar(&assumeRoleName, "assumeRoleName", "", "The dataplane role cluster-controller assumed to manage dataplane resources")
	rootCmd.PersistentFlags().StringVar(&readonlyAssumeRoleName, "readonlyAssumeRoleName", "", "The readonly dataplane role cluster-controller assumed to view dataplane resources")
	rootCmd.PersistentFlags().StringVar(&awsClusterServerRoleARN, "awsClusterServerRoleARN", "", "The IAM role ARN of cluster-server")
	rootCmd.PersistentFlags().StringVar(&gcpClusterServerSAName, "gcpClusterServerSAName", "", "The IAM SA of cluster-server")
	rootCmd.PersistentFlags().StringVar(&overrideRegistry, "overrideRegistry", "", "The docker image registry domain name, eg. ***.dkr.ecr.us-west-2.amazonaws.com")
	rootCmd.PersistentFlags().StringVar(&overrideHelperImage, "overrideHelperImage", "", "The full path for busybox helper image")
}

// rootCmd represents the base command when called without any subcommands
var rootCmd = &cobra.Command{
	Use:   "eks-provider",
	Short: "infra providers(eks/gke)",
	RunE: func(cmd *cobra.Command, args []string) error {
		if enableCMControllers {
			RunCMControllers()
		} else if enableDPControllers {
			// for compatibility with old version, the old flag`enable-dp-controllers` means  to running import controllers.
			runImportControllers()
		} else {
			return errors.New("problem running manager both enable-cm-controllers and enable-dp-controllers are false")
		}
		return nil
	},
}

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