package main

import (
	"proxy/canal"
	config2 "proxy/config"
	"proxy/cron"
	"proxy/provision"
	_ "time"

	l4g "github.com/sirupsen/logrus"
	mysql "proxy/Nmysql"
	rdb "proxy/Nredis"
	rest "proxy/Nrestful"
	tn "proxy/TelnetShellServer"
	"proxy/logger"
)
/*
func initLog(cfg *rest.LogConf) {
	if strings.Compare("file", cfg.Output) != 0 {
		l4g.SetOutput(os.Stdout)
	} else {
		path := cfg.Path// "/var/log/pcf.log"
		// log rotate
		//`WithLinkName` 为最新的日志建立软连接
		//`WithRotationTime` 设置日志分割的时间，隔多久分割一次
		//WithMaxAge 和 WithRotationCount二者只能设置一个
		//  `WithMaxAge` 设置文件清理前的最长保存时间
		//  `WithRotationCount` 设置文件清理前最多保存的个数
		//
		// add a new log every 3 hours, with 30 days at most.
		writer, _ := rotatelogs.New(
			path+".%Y-%m-%d-%H:%M",
			rotatelogs.WithLinkName(path),
			//rotatelogs.WithMaxAge(time.Duration(cfg.MaxAge)*time.Hour),
			//rotatelogs.WithRotationTime(time.Duration(cfg.RotationTime)*time.Hour),
			rotatelogs.WithRotationTime(3 * time.Hour),
			rotatelogs.WithRotationCount(uint(cfg.MaxAge)),
		)
		l4g.SetOutput(writer)
	}
	
	if strings.Compare("debug", cfg.Level) == 0 {
		l4g.SetLevel(l4g.DebugLevel)
	} else if strings.Compare("info", cfg.Level) == 0 {
		l4g.SetLevel(l4g.InfoLevel)
	} else if strings.Compare("warn", cfg.Level) == 0 {
		l4g.SetLevel(l4g.WarnLevel)
	} else if strings.Compare("error", cfg.Level) == 0 {
		l4g.SetLevel(l4g.ErrorLevel)
	}
	//l4g.SetReportCaller(true)// useless
	//l4g.SetFormatter(&l4g.TextFormatter{})
}*/

func check(err error, message string) {
	if err != nil {
		panic(err)
	}

	initLog.Debugf("%s", message)
}

// ******************************************************************
var initLog *l4g.Entry
func init() {
	initLog = logger.InitLog
}

func setLogLevel(level string) {
	if level != "" {
		level, err := l4g.ParseLevel(level)
		if err != nil {
			initLog.Warnf("Log level [%s] is invalid, set to [info] level",
				level)
			logger.SetLogLevel(l4g.InfoLevel)
		} else {
			initLog.Infof("Log level is set to [%s] level", level)
			logger.SetLogLevel(level)
		}
	} else {
		initLog.Infoln("Log level not set. Default set to [info] level")
		logger.SetLogLevel(l4g.InfoLevel)
	}

	logger.SetReportCaller(true)
}
// *********************************************************************************

//var cfgFile = flag.String("c", "", "selfcare proxy configure file.")
func main() {
	// check if billing already running
	/*var output, errout string
	err, output, errout := rest.Shellout("pidof billing")
    if err != nil {
    	fmt.Printf("Get pid of billing fail, err: %v\n", err)
    } else {
    	ss := strings.Fields(output)
    	if len(ss) >= 2 {
    		fmt.Printf("Process billing is already running, pids[%s], exit!\n", output)
    		os.Exit(0)
    	} else {
    		fmt.Printf("First process of billing, stdout[%s], stderr[%s]!\n", output, errout)
    	}
    }*/

	//flag.Parse()

	// read config
	config := &config2.Config
	err := config2.ReadConfig()
	if err != nil {
		initLog.Errorf("open config file error: %s", err)
		return
	} else {
		initLog.Infof("config file: %v", config)
	}

	//initLog(&config.Log)
	setLogLevel(config.Log.Level)
	
	initLog.Infof("selfcare proxy start...\r\nconfig:[%v]", config)

	if config.Rest.Enabled {
		go rest.Connect_ocs(config.Rest.LocRzIp, config.Rest.OcsRzIp, config.Rest.LocRzPort, config.Rest.OcsRzPort)
		go rest.StartHttpServer(config.Rest.HttpAddr)
	}

	go tn.Server(config.TelnetServer.Addr)

	// temp disable======================
	go rdb.NewRedisClient(config.RedisDb.NetType, config.RedisDb.Addr, config.RedisDb.Password, config.RedisDb.SentinelAddrs)

	go mysql.OpenMysql(config.MysqlDb.Username, config.MysqlDb.Password, config.MysqlDb.Addr)
	if config.CanalServer.Enabled {
		go canal.CanalFsm(config.CanalServer.Addr, config.CanalServer.Username, config.CanalServer.Password)
	}
	//

	if config.CronCfg.Enabled && (config.CronCfg.ClrExp != "" || config.CronCfg.NtfSms != "") {
		cron.CronStart(config.CronCfg.ClrExp, config.CronCfg.NtfSms)
		defer cron.CronStop()
	}

	go provision.ProvisionFsm()

	select {}
}
