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 adserver() {	
		// 1 初始化 微盘复制状态
		public.CopyStatusWeDrive = make(map[string]bool)
		public.CopyStatusWeDrive[public.Zhiwei_Dept_HB]	 	= true
		public.CopyStatusWeDrive[public.Zhiwei_Dept_LP]	 	= true
		public.CopyStatusWeDrive[public.Zhiwei_Dept_JR]	 	= true
		public.CopyStatusWeDrive[public.Zhiwei_Dept_JD]		= true
		public.CopyStatusWeDrive[public.Zhiwei_Dept_TXHD]	= true
		public.CopyStatusWeDrive[public.Zhiwei_Dept_TXWJ]	= true
		public.CopyStatusWeDrive[public.Zhiwei_Dept_BGYJZX]	= true
		public.CopyStatusWeDrive[public.Zhiwei_Dept_TECH]	= true

	} else {
		// 1 发送 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
}
