package main

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

	"git.loafle.net/commons/configuration-go"
	"git.loafle.net/commons/logging-go"
	"git.loafle.net/overflow/member_gateway_rest/config"
	"git.loafle.net/overflow/member_gateway_rest/server"
	"git.loafle.net/overflow/member_gateway_rest/service"
	"io/ioutil"
	"path"
	"github.com/dgrijalva/jwt-go"
)

var (
	configDir *string
)

func init() {
	configDir = flag.String("config-dir", "./", "Config directory")
	logConfigPath := flag.String("log-config", "", "logging config path")
	flag.Parse()

	logging.InitializeLogger(*logConfigPath)
}

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

	loadKey(*configDir, _config)

	service.InitPackage()
	defer func() {
		service.DestroyPackage()
	}()

	s := server.NewServer(_config)

	go func() {
		err := s.ListenAndServe()
		if nil != err {
			log.Printf("err: %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()
	if err := s.Shutdown(ctx); err != nil {
		logging.Logger().Errorf("error: %v", err)
	}
}

func loadKey(configDir string, _config *config.Config)  {

	signBytes, err := ioutil.ReadFile(path.Join(configDir, "overFlow-private.key"))
	if nil != err {
		logging.Logger().Panic(err)
	}

	_config.SignKey, err = jwt.ParseRSAPrivateKeyFromPEM(signBytes)
	if nil != err {
		logging.Logger().Panic(err)
	}

	verifyBytes, err := ioutil.ReadFile(path.Join(configDir, "overFlow-public.pem"))
	if nil != err {
		logging.Logger().Panic(err)
	}

	_config.VerifyKey, err = jwt.ParseRSAPublicKeyFromPEM(verifyBytes)
	if nil != err {
		logging.Logger().Panic(err)
	}
}

