package main

import (
	"context"
	"flag"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"

	"bsm/full/all/internal/config"
	"bsm/full/all/internal/impl"
	allserver "bsm/full/all/internal/server"
	"bsm/full/all/internal/service"

	"git.apinb.com/bsm-sdk/core/utils"
)

var ServiceKey = "default"

func main() {
	workspace := flag.String("workspace", ServiceKey, "workspace used to select etc/{workspace}_{runtime}.yaml")
	flag.Parse()
	value, err := utils.MustString(*workspace)
	if err != nil {
		panic(err)
	}
	ServiceKey = value

	config.New(ServiceKey)
	impl.NewImpl()

	srv := allserver.New()
	if err := service.Expose(srv); err != nil {
		panic(err)
	}

	stop := make(chan os.Signal, 1)
	signal.Notify(stop, syscall.SIGINT, syscall.SIGTERM)
	go func() {
		<-stop
		ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
		defer cancel()
		_ = srv.Stop(ctx)
	}()

	if err := srv.Start(config.Spec.Server.GRPC.Addr, config.Spec.Server.HTTP.Addr, config.Spec.DynamicRPC.Allow); err != nil && err != http.ErrServerClosed {
		panic(err)
	}
}
