package main

import (
	"time"

	baseapp "hnyfkj.com.cn/rtu/linux/baseapp"
	netmgrd "hnyfkj.com.cn/rtu/linux/netmgrd"
)

const MODULE_NAME = "TimeSync"

func main() {
	baseapp.InitLogger("")

	for {
		_, pingOK, tcpOK, _, httpTime := netmgrd.CheckNetwork()

		netOK := tcpOK || pingOK
		if !netOK {
			time.Sleep(time.Second)
			continue
		}

		var err error
		if !httpTime.IsZero() { // 优先使用HTTP时间, 实测速度快且精度高
			err = netmgrd.SetSystemTime(httpTime)
		}

		if httpTime.IsZero() || err != nil {
			err = netmgrd.SyncNTPTime() // 同步HTTP时间失败, 尝试NTP同步
		}

		if err != nil {
			baseapp.Logger.Errorf("[%s] Error synchronizing system time: %v!!", MODULE_NAME, err)
			time.Sleep(time.Second)
			continue
		}

		baseapp.Logger.Infof("[%s] ✅ System time synchronized successfully: %s", MODULE_NAME, time.Now().Format("2006-01-02 15:04:05"))
		time.Sleep(time.Hour)
	}
}
