package main

import (
	"fmt"
	"github.com/cron"
	"log"
	"net/http"
	"net/url"
	"os"
	"os/exec"
	qu "qfw/util"
	"runtime"
	"strconv"
	"strings"
	"time"
)

var (
	sysconfig			map[string]interface{} //配置文件
	vpsID,during		string			//机器唯一标识
	processArr 			[]string		//机器相关下载器

)

func init()  {
	qu.ReadConfig(&sysconfig)
	vpsID = qu.ObjToString(sysconfig["vpsID"])
	during = qu.ObjToString(sysconfig["during"])
	processArr = qu.ObjArrToStringArr(sysconfig["processArr"].([]interface{}))
}


func main() {

	if vpsID == "" || len(processArr) < 1 {
		log.Println("配置文件异常，请检查......")
		os.Exit(1)
	}

	//定时器
	c := cron.New()
	spec := fmt.Sprintf("0 */%s * * * ?",during)	//分
	//spec =fmt.Sprintf("*/%s * * * * ?",during)		//秒
	c.AddFunc(spec, func() { task() })
	c.Start()
	time.Sleep(99999 * time.Hour)
}

func task()  {
	log.Println("执行...检测...")
	//先检测下载器
	process := "0" //正常 - windows模式
	for _,v:=range processArr {
		if runtime.GOOS == "windows" {
			b,_,_ := isProcessExist(v)
			if !b {
				process = "1"
				break
			}
		}else { //linux测试使用
			b,_:=checkProRunning(v)
			if !b {
				process = "1"
				break
			}
		}
	}
	//log.Println("当前下载器：",process)
	//u, _ := url.Parse("http://127.0.0.1:7811") //本地测试
	u, _ := url.Parse("http://monitor.spdata.jianyu360.com") //线上
	q := u.Query()
	q.Set("id", vpsID)
	q.Set("process", process)
	u.RawQuery = q.Encode()

	//log.Println(vpsID,process)

	_, err := http.Get(u.String());
	if err != nil {
		log.Println("异常",err)
	}

}






/****************分割线******************/
/****************分割线******************/
/****************分割线******************/



//根据进程名判断进程是否运行
func checkProRunning(serverName string) (bool, error) {
	cmd := `ps ux | awk '/` + serverName + `/ && !/awk/ {print $2}'`
	pid, err := runInLinux(cmd)
	if err != nil {
		return false, err
	}
	return pid != "", nil
}
//根据进程名称获取进程ID
func getPid(serverName string) (string, error) {
	cmd := `ps ux | awk '/` + serverName + `/ && !/awk/ {print $2}'`
	pid, err := runInLinux(cmd)
	return pid , err
}
//
func runInLinux(cmd string) (string, error) {
	result, err := exec.Command("/bin/sh", "-c", cmd).Output()
	if err != nil {
		return "", err
	}
	return strings.TrimSpace(string(result)), err
}

func isProcessExist(appName string) (bool, string, int) {
	appary := make(map[string]int)
	cmd := exec.Command("cmd", "/C", "tasklist")
	output, _ := cmd.Output()
	//fmt.Printf("fields: %v\n", output)
	n := strings.Index(string(output), "System")
	if n == -1 {
		//log.Println("no find")
		//os.Exit(1)
	}
	data := string(output)[n:]
	fields := strings.Fields(data)
	for k, v := range fields {
		if v == appName {
			appary[appName], _ = strconv.Atoi(fields[k+1])

			return true, appName, appary[appName]
		}
	}
	return false, appName, -1
}