package main

import (
	"flag"
	"git.quantgroup.cn/DevOps/enoch/service"
	"git.quantgroup.cn/DevOps/enoch/service/conf"
	"git.quantgroup.cn/DevOps/enoch/service/consumer"
	"git.quantgroup.cn/DevOps/enoch/service/continuous_queries"
	"git.quantgroup.cn/DevOps/enoch/service/data"
	"git.quantgroup.cn/DevOps/enoch/service/file_cache"
	"git.quantgroup.cn/DevOps/enoch/service/job"
	"git.quantgroup.cn/DevOps/enoch/service/node-check"
	"github.com/vrg0/go-common/logger"
	"net/http"
	_ "net/http/pprof"
	"os"
	"strconv"
)

var quartz bool
var denv string
var didc string

func init() {
	flag.BoolVar(&quartz, "quartz", false, "quartz")
	flag.StringVar(&denv, "env", "dev", "环境")
	flag.StringVar(&didc, "idc", "local", "机房")
	flag.Parse()

	logPath := "./enoch.log"
	if denv == "pro" {
		logPath = "/home/quant_group/enoch/enoch.log"
	}

	if e := logger.Init(denv == "pro", logPath); e != nil {
		panic(e)
	}
}

func main() {
	conf.Load(denv, didc)

	file, err := os.OpenFile("quantgroup.log", os.O_RDWR|os.O_CREATE, 0666)
	defer func() { _ = file.Close() }()
	if err != nil {
		logger.Fatal("create file error", err)
	}
	file_cache.Load(conf.GlobalConfig.FileCachePath)
	file_cache.RegisterJob(consumer.ReSubmit)
	go file_cache.Delete()
	port := conf.GlobalConfig.Port

	logger.Info(conf.GlobalConfig.AppName + "项目启动, port:" + port + ",环境:" + conf.GlobalConfig.Env)
	defer logger.Info("项目结束")

	//初始化redis连接池
	data.RedisPoolInit()
	go consumer.AgentClusterConsumer(conf.HealthTopic(), consumer.HealthMessageHandler{})
	go consumer.AgentClusterConsumer(conf.BraveTopic(), consumer.BraveMessageHandler{})
	intPort, _ := strconv.Atoi(port)

	if quartz {
		logger.Info("启动定时任务")
		job.AutoEmailPerformInfo()
	}

	//开启服务状态监控，当服务状态异常时，调用web-hook函数
	if denv == "dev" {		//开发环境
		go node_check.NodeCheck()
		job.AutoAlarm()
	} else if job.CheckIp("172.30.12.22") {  //生产环境，只有172.30.12.22执行
		go node_check.NodeCheck()
		job.AutoAlarm()
		continuous_queries.Load()		//连续查询设置只在生产环境上执行
	}

	go func() {
		_ = http.ListenAndServe("0.0.0.0:"+strconv.Itoa(intPort+1), nil)
	}()

	http.HandleFunc("/duration", service.DurationInterface)
	http.HandleFunc("/tech/health/check", func(writer http.ResponseWriter, request *http.Request) {
		writer.WriteHeader(http.StatusOK)
	})
	http.HandleFunc("/counter", service.CounterInterface)

	err = http.ListenAndServe(":"+port, nil)
	if err != nil {
		logger.Fatal("服务启动失败", err)
	}

}


