package main

import (
	"../nt"
	"../prof"
	"./pb"
	"context"
	"flag"
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
	"os"
	"os/signal"
	"runtime"
	"syscall"
	"time"
)

var (
	ChQuit chan struct{}   = make(chan struct{}) // 进程退出通知
	E      map[pb.Ec]error = make(map[pb.Ec]error)
)

func main() {
	en := BuildErrors()
	fmt.Println("load errors defination num:", en)

	runtime.GOMAXPROCS(runtime.NumCPU())

	// 解析参数
	FileConf = flag.String("c", "conf.json", "config file")
	flag.Parse()

	//
	init_by_conf()
	//
	if err := LoadRedisLua(); err != nil {
		panic("load redis lua failed")
	}
	//
	profile := prof.NewProf(nt.InstConf.ProfAddr, true)
	//
	gin.SetMode(nt.InstConf.Mode)

	// 路由
	router := GetRouter()
	//
	addr := fmt.Sprintf("%s:%d", nt.InstConf.Host, nt.InstConf.Port)
	server := &http.Server{
		Addr:    addr,
		Handler: router,
	}
	go func() {
		// 开启服务
		if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			fmt.Println("listen error:", err)
		}
	}()

	nt.PrintInstInfo(nt.Mac)

	// 退出方式
	chSig := make(chan os.Signal)
	signal.Notify(chSig, syscall.SIGINT, syscall.SIGTERM)

	fmt.Println("Signal:", <-chSig) // will be blocked here

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

	if err := server.Shutdown(ctx); err != nil {
		fmt.Println("Server shutdown error:", err)
	}
	select {
	case <-ctx.Done():
		fmt.Println("Timeout and quit")
	}

	profile.Stop()
	//
	close(ChQuit)

	fmt.Println("Server Exited.")
}
