package main

import (
	"bytes"
	"encoding/json"
	"flag"
	"fmt"
	"io/ioutil"
	"os/exec"
	"strings"
	"time"
)


var configPath = flag.String("c", "", "Config file path");

type appConfig struct {
    Cmd string `json:"cmd"`
    Watch []string `json:"watch"`
    Path string `json:"path"`
    Php string `json:"php"`
}


func exec_shell(s string) (string, error) {
	cmd := exec.Command("/bin/bash", "-c", s)
    var out bytes.Buffer
	cmd.Stdout = &out
    err := cmd.Run()
	return out.String(), err
}

func getConfig(configPath string) (appConfig, error) {
    file, err := ioutil.ReadFile(configPath);
	if err != nil {
		panic(err)
	}
    var config appConfig;
    err = json.Unmarshal(file, &config)
	if err != nil {
		panic(err)
	}
    return config, nil;
}

func main() {
	defer func() {
		if err := recover(); err != nil {
			fmt.Println(err)
		}
	}()
	flag.Parse();
	config, err  := getConfig(*configPath);
	if err != nil {
		fmt.Errorf(err.Error())
		return;
	}
	out, _ := exec_shell(config.Cmd)
	outs := strings.Split(out, "\n")
	keys  := make(map[string]bool);
	for _, key := range config.Watch {
		keys[key] = false;
	}
	for _,v := range outs {
		for _, key := range config.Watch {
			if strings.Index(v, key) >= 0 {
				keys[key] = true;
			}
		}
	}
	var command *exec.Cmd
	y,m,d := time.Now().Date()
	f := fmt.Sprintf("%d-%d-%d", y,m,d);
	for key,result := range keys {
		if result == false {
			command = exec.Command(config.Php, config.Path, key, "> /root/monitors/logs/monitor-"+f+".log")
			command.Run()
		}
	}
}