package main

import (
	"flag"
	"os"
	"path/filepath"

	"github.com/spf13/viper"
	"github.com/tidbcloud/service-catalog/pkg/api"
	"github.com/tidbcloud/service-catalog/pkg/controller"
	"github.com/tidbcloud/service-catalog/pkg/prom"
	"github.com/tidbcloud/tiinf/monitor/tilog"
	"github.com/tidbcloud/tiinf/monitor/titracing"
	"go.uber.org/zap"
	"k8s.io/client-go/rest"
	"k8s.io/client-go/tools/clientcmd"
)

var (
	masterURL  string
	kubeconfig string
)

func main() {
	tilog.PlainInfo("Service Catalog started.")
	viper.SetConfigName("config")
	viper.SetConfigType("yaml")
	viper.AddConfigPath("/etc/service-catalog")
	err := viper.ReadInConfig()
	if err != nil {
		panic(err)
	}

	flag.StringVar(&kubeconfig, "kubeconfig", defaultKubeconfig(), "Path to a kubeconfig. Only required if out-of-cluster.")
	flag.StringVar(&masterURL, "master", "", "The address of the Kubernetes API server. Overrides any value in kubeconfig. Only required if out-of-cluster.")
	flag.Parse()
	cfg, err := rest.InClusterConfig()
	if err != nil {
		cfg, err = clientcmd.BuildConfigFromFlags(masterURL, kubeconfig)
		if err != nil {
			tilog.PlainFatal("Error building kubeconfig", zap.Error(err))
		}
	}
	controller.Init(cfg)
	tilog.PlainInfo("Service Catalog started - controller init completed.")

	err = api.Init()
	if err != nil {
		panic(err)
	}

	tilog.PlainInfo("Service Catalog started - api init completed.")
	err = prom.Init(viper.GetString("env"))
	if err != nil {
		tilog.PlainFatal("failed to init prom client", zap.Error(err))
	}

	_, err = titracing.InitJaeger("service-catalog")
	if err != nil {
		panic(err)
	}

	tilog.PlainInfo("Service Catalog started - prom&jaeger init completed.")
	api.RunServer()
}

func defaultKubeconfig() string {
	fname := os.Getenv("KUBECONFIG")
	if fname != "" {
		return fname
	}
	home, err := os.UserHomeDir()
	if err != nil {
		tilog.PlainWarn("failed to get home directory", zap.Error(err))
		return ""
	}
	return filepath.Join(home, ".kube", "config")
}
