package main

import (
	"context"
	"log"
	"oc-discovery/conf"
	"oc-discovery/daemons/node"
	"os"
	"os/signal"
	"strings"
	"syscall"

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

const appname = "oc-discovery"

func main() {
	// Init the oc-lib
	oclib.InitDaemon(appname)
	// get the right config file

	o := oclib.GetConfLoader(appname)

	conf.GetConfig().Name = o.GetStringDefault("NAME", "opencloud-demo")
	conf.GetConfig().Hostname = o.GetStringDefault("HOSTNAME", "127.0.0.1")
	conf.GetConfig().PSKPath = o.GetStringDefault("PSK_PATH", "./psk/psk.key")
	conf.GetConfig().NodeEndpointPort = o.GetInt64Default("NODE_ENDPOINT_PORT", 4001)
	conf.GetConfig().IndexerAddresses = o.GetStringDefault("INDEXER_ADDRESSES", "")

	conf.GetConfig().NanoIDS = o.GetStringDefault("NANO_IDS", "")
	conf.GetConfig().PeerIDS = o.GetStringDefault("PEER_IDS", "")

	conf.GetConfig().NodeMode = o.GetStringDefault("NODE_MODE", "node")

	conf.GetConfig().MinIndexer = o.GetIntDefault("MIN_INDEXER", 1)
	conf.GetConfig().MaxIndexer = o.GetIntDefault("MAX_INDEXER", 5)
	conf.GetConfig().LocationGranularity = o.GetIntDefault("LOCATION_GRANULARITY", 2)

	ctx, stop := signal.NotifyContext(
		context.Background(),
		os.Interrupt,
		syscall.SIGTERM,
	)
	defer stop()
	isNode := strings.Contains(conf.GetConfig().NodeMode, "node")
	isIndexer := strings.Contains(conf.GetConfig().NodeMode, "indexer")
	if n, err := node.InitNode(isNode, isIndexer); err != nil {
		panic(err)
	} else {
		<-ctx.Done() // the only blocking point
		log.Println("shutting down")
		n.Close()
	}
}
