package main

import (
	stdLog "log"
	"os"
	"os/signal"
	"syscall"

	"go.uber.org/zap"
	"git.ssns.se/git/frozendragon/minecraft-ui/internal/service"
	"git.ssns.se/git/frozendragon/minecraft-ui/internal/config"
	"git.ssns.se/git/frozendragon/minecraft-ui/internal/env"
)

func main() {
	conf, err := config.New(env.OS)
	if err != nil {
		stdLog.Fatalln("Failed to instantiate configuration:", err)
	}

	defer func() {
		// Ignore potential error result, see https://github.com/uber-go/zap/issues/370
		_ = conf.Logger.Sync()
	}()

	conf.Logger.Info("Instantiating service")
	svc, err := service.New(conf)
	if err != nil {
		conf.Logger.Fatal("Failed to instantiate service", zap.Error(err))
	}

	go func() {
		conf.Logger.Info("Starting service")
		if err := svc.Start(); err != nil { // blocks
			conf.Logger.Error("Error while running service", zap.Error(err))
		}
	}()

	sig := awaitSignals()
	conf.Logger.Info("Received signal", zap.String("signal", sig.String()))

	conf.Logger.Info("Stopping service")
	if err := svc.Stop(); err != nil {
		conf.Logger.Error("Failed to stop service", zap.Error(err))
	}

	conf.Logger.Info("Stopped service")
}

// See https://devcenter.heroku.com/articles/dynos#graceful-shutdown-with-sigterm
func awaitSignals() os.Signal {
	ch := make(chan os.Signal, 1)
	signal.Notify(ch, syscall.SIGTERM, os.Interrupt)
	return <-ch
}