package main

import (
	"context"
	"os"
	"os/signal"
	"syscall"
	"time"

	"git.loafle.net/commons/configuration-go"
	cdr "git.loafle.net/commons/di-go/registry"
	"git.loafle.net/commons/logging-go"
	cssw "git.loafle.net/commons/server-go/socket/web"
	occp "git.loafle.net/overflow/commons-go/config/probe"
	occi "git.loafle.net/overflow/commons-go/core/interfaces"
	"git.loafle.net/overflow/probe/auth"
	"git.loafle.net/overflow/probe/config"
	"git.loafle.net/overflow/probe/probe"
)

func init() {
	logging.InitializeLogger(config.ProbeLoggingConfigFilePath())
}

func main() {
	_config := &config.Config{}
	if err := configuration.Load(_config, config.ProbeConfigFilePath()); nil != err {
		logging.Logger().Panic(err)
	}

	cdr.RegisterResource(config.ConfigKey, _config)

	var instance interface{}
	var err error

	go func() {
		if occp.ProbeStateTypeNotAuthorized == _config.Probe.State() {
			instance = &auth.Authenticator{}
			doneChan, err := instance.(occi.EndableStarter).EndableStart()
			if nil != err {
				logging.Logger().Error(err)
				os.Exit(1)
			}
			var ok bool
			err, ok = <-doneChan
			if !ok {
				return
			}
			if nil != err {
				logging.Logger().Error(err)
				os.Exit(1)
			}
			if err := instance.(occi.Stopper).Stop(context.Background()); err != nil {
				logging.Logger().Errorf("error: %v", err)
			}
		}

		p := probe.New()
		instance = p
		err = p.ListenAndServe()
		if nil != err {
			logging.Logger().Error(err)
			os.Exit(1)
		}

		if err := p.Shutdown(context.Background()); err != nil {
			logging.Logger().Errorf("error: %v", err)
		}
	}()

	interrupt := make(chan os.Signal, 1)
	signal.Notify(interrupt,
		syscall.SIGKILL,
		syscall.SIGSTOP,
		syscall.SIGHUP,
		syscall.SIGINT,
		syscall.SIGTERM,
		syscall.SIGQUIT)

	<-interrupt
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()

	switch v := instance.(type) {
	case *auth.Authenticator:
		err = v.Stop(ctx)
	case *cssw.Server:
		err = v.Shutdown(ctx)
	}

	if err != nil {
		logging.Logger().Errorf("error: %v", err)
	}
}
