package main

import (
	pub "AD-Control/public"
	"net"
	"io"
	"bufio"
)

// 守护进程 初始化
func daemonInit(){
	// 1 创建文件夹
	for _,i := range pub.Dir_Be{
		if pub.NotExist(i){
			pub.Mkdir(i)
		}
	}
	
	var logpath string
	if pub.Adserver() {	
		// 2 初始化 微盘复制状态
		pub.CopyStatusWeDrive = make(map[string]bool)
		pub.CopyStatusWeDrive[pub.Zhiwei_Dept_HB]	 	= true
		pub.CopyStatusWeDrive[pub.Zhiwei_Dept_LP]	 	= true
		pub.CopyStatusWeDrive[pub.Zhiwei_Dept_JR]	 	= true
		pub.CopyStatusWeDrive[pub.Zhiwei_Dept_JD]		= true
		pub.CopyStatusWeDrive[pub.Zhiwei_Dept_TXHD]		= true
		pub.CopyStatusWeDrive[pub.Zhiwei_Dept_TXWJ]		= true
		pub.CopyStatusWeDrive[pub.Zhiwei_Dept_BGYJZX]	= true
		pub.CopyStatusWeDrive[pub.Zhiwei_Dept_TECH]		= true

		// 日志文件位置：主控源文件的源文件目录
		logpath = `C:\Users\Administrator\go\src\AD-Control\logs\daemon.log`
	} else {
		// 日志文件位置：域计算机的备份目录:C:\windows\temp
		logpath = pub.Dir_tmp + `\daemon.log`
	}

	//3 写入日志
	pub.Loger = pub.NewLoger(logpath)
}

// 守护进程 运行
func deamonRun(){
	daemonHost := pub.User_computername
	listener, err := net.Listen("tcp", pub.DaemonListen)
	if err != nil {
		pub.PntError("Listen Error ", err)
		return
	}
	defer listener.Close()

	for{
		if conn, err := listener.Accept(); err == nil {
			// 新建 读取流
			if bmsg,cerr:= bufio.NewReader(conn).ReadBytes(pub.EndSign) ; cerr != io.EOF {

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

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

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

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

}

func main() {
	daemonInit()
	deamonRun()
}

