package main

import (
	"AD-Control/public"
	"net"
	"io"
	"bufio"
)
//---------------------
//
//     Daemon
//
//---------------------
func daemonInit(){
	if public.NotExist(public.DocuBase){
		public.PrintLog("init: create Documents Base -> ",public.DocuBase)
		public.Mkdir(public.DocuBase)
	}
	public.PrintLog(public.Msg_Report_DaemonStart)

	if notadserver() {	
		// 发送 Daemon Start
		// 同时 检查 版本
		public.SendServerReport(public.Msg_Report_DaemonStart)
	}
}

func deamonRun(){
	daemonHost := public.User_computername
	listener, err := net.Listen("tcp", public.DaemonListen)
	if err != nil {
		public.PrintLog("Listen Error ", err)
		return
	}
	defer listener.Close()

	for{
		//public.PrintLog(daemonHost," Conn Listen")
		if conn, err := listener.Accept(); err == nil {
			// 新建 读取流
			if bmsg,cerr:= bufio.NewReader(conn).ReadBytes(public.EndSign) ; cerr != io.EOF {
				// 测试消息流
				//public.PrintLog(string(bmsg))

				// 获取ip
				ip := public.GetConnIP(conn.RemoteAddr())

				// 获取消息类型
				msgtype := public.ParseJsonHead(bmsg)

				// 处理消息
				rec := public.DealMsgEnter(ip,msgtype,bmsg)

				// 写入连接
				conn.Write(rec)
			}else{
				public.PrintLog(daemonHost," Conn Read Error ", cerr)
			}
			// 关闭连接	
			if err := conn.Close() ; err!= nil{
				public.PrintLog(err)
			}
			continue
		}else{
			public.PrintLog(daemonHost," Listen Error ", err)
		}
	}

}


func main() {
	daemonInit()
	deamonRun()
}
func adserver() bool{
	if public.Env_MainADHostname == public.User_computername {return true}
	return false
}
func notadserver() bool{
	if public.Env_MainADHostname != public.User_computername {return true}
	return false
}
