package main

import (
	"flag"
	"os"
	"os/signal"

	"git.ctrlz.es/mgdelacroix/craban/server"

	"github.com/rs/zerolog/log"
)

func main() {
	configFlag := flag.String("config", "craban.yml", "the configuration path")
	flag.Parse()

	srv, err := server.NewServerWithConfigPath(*configFlag)
	if err != nil {
		log.Error().Err(err).Msg("cannot create server")
		os.Exit(1)
	}

	c := make(chan os.Signal, 1)
	signal.Notify(c, os.Interrupt)
	closed := make(chan bool, 1)

	go func() {
		log.Info().Msg("Starting craban server")
		if err := srv.Start(); err != nil {
			log.Error().Err(err).Msg("error running server")
			os.Exit(1)
		}
		closed <- true
	}()

	s := <-c
	log.Info().Str("signal", s.String()).Msg("got signal, exiting")
	if err := srv.Close(); err != nil {
		log.Error().Err(err).Msg("error closing server")
		os.Exit(1)
	}
	<-closed
}
