package main

import (
	//"github.com/lxn/walk"
	"AD-Control/public"
	"net"
	"io"
	"bufio"
)
//---------------------
//
//     Daemon
//
//---------------------
func daemonInit(){
	if !public.Exists(public.DocuBase){
		public.PrintLog("init: create Documents Base -> ",public.DocuBase)
		public.Mkdir(public.DocuBase)
	}
	public.PrintLog(public.Env_computername," Daemon start")

	if notadserver() {	
		public.SendServerExec(public.Version)
		public.SendServerReport(public.Env_computername + " Daemon start")
	}
}

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

	for{
		public.DebugLog(daemonHost," Conn Listen")
		if conn, err := listener.Accept(); err == nil {
			// 新建 读取流
			if bmsg,cerr:= bufio.NewReader(conn).ReadBytes(public.EndSign) ; cerr != io.EOF {
				// 测试消息流
				public.DebugLog(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.Env_computername {return true}
	return false
}
func notadserver() bool{
	if public.Env_MainADHostname != public.Env_computername {return true}
	return false
}
