package main

import (
	"fmt"
	"oc-schedulerd/conf"
	"oc-schedulerd/daemons"
	"os"

	oclib "cloud.o-forge.io/core/oc-lib"
)

func main() {
	oclib.InitDaemon("oc-schedulerd")
	l := oclib.GetLogger()
	o := oclib.GetConfLoader()

	c := oclib.SetConfig(
		o.GetStringDefault("MONGO_URL", "mongodb://127.0.0.1:27017"),
		o.GetStringDefault("MONGO_DATABASE", "DC_myDC"),
		o.GetStringDefault("NATS_URL", "nats://localhost:4222"),
		o.GetStringDefault("LOKI_URL", ""),
		o.GetStringDefault("LOG_LEVEL", "info"),
	)

	conf.GetConfig().DBName = c.MongoDatabase
	conf.GetConfig().MongoUrl = c.MongoUrl
	conf.GetConfig().NatsUrl = c.NATSUrl
	conf.GetConfig().LokiUrl = c.LokiUrl
	conf.GetConfig().Mode = o.GetStringDefault("MODE", "")

	if conf.GetConfig().Mode == "container" {
		conf.GetConfig().KubeHost = o.GetStringDefault("KUBERNETES_SERVICE_HOST", os.Getenv("KUBERNETES_SERVICE_HOST"))
		conf.GetConfig().KubePort = o.GetStringDefault("KUBERNETES_SERVICE_PORT", "6443")

		conf.GetConfig().KubeCA = o.GetStringDefault("KUBE_CA", os.Getenv("KUBE_CA"))
		conf.GetConfig().KubeCert = o.GetStringDefault("KUBE_CERT", os.Getenv("KUBE_CERT"))
		conf.GetConfig().KubeData = o.GetStringDefault("KUBE_DATA", os.Getenv("KUBE_DATA"))
	}

	// Test if oc-monitor binary is reachable
	// For local executions
	if _, err := os.Stat("../oc-monitord/oc-monitord"); err == nil {
		conf.GetConfig().MonitorPath = "../oc-monitord/oc-monitord"
	}
	// For container executions
	if _, err := os.Stat("/usr/bin/oc-monitord"); conf.GetConfig().MonitorPath == "" && err == nil {
		conf.GetConfig().MonitorPath = "/usr/bin/oc-monitord"
	}

	if conf.GetConfig().MonitorPath == "" {
		l.Fatal().Msg("Could not find oc-monitord binary")
	}

	l.Info().Msg("oc-monitord binary at " + conf.GetConfig().MonitorPath)

	sch_mngr := daemons.ScheduleManager{Logger: oclib.GetLogger()}
	exe_mngr := daemons.ExecutionManager{}

	go sch_mngr.ListenNATS()
	go sch_mngr.SchedulePolling()

	exe_mngr.RetrieveNextExecutions()

	fmt.Print("stop")
}
