//go:generate go run -mod=vendor git.rootprojects.org/root/go-gitver

// Watchdog Binary
package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"log"
	"os"
	"strings"

	"git.rootprojects.org/root/watchdog.go"
)

var GitRev, GitVersion, GitTimestamp string

func usage() {
	fmt.Println("Usage: watchdog -c config.json")
}

func main() {
	for i := range os.Args {
		switch {
		case strings.HasSuffix(os.Args[i], "version"):
			fmt.Println(GitTimestamp)
			fmt.Println(GitVersion)
			fmt.Println(GitRev)
			os.Exit(0)
		case strings.HasSuffix(os.Args[i], "help"):
			usage()
			os.Exit(0)
		case os.Args[i] == "install":
			args := []string{}
			if len(os.Args) > i+1 {
				args = os.Args[i+1:]
			}
			install(os.Args[0], args)
			os.Exit(0)
		}
	}

	if 3 != len(os.Args) {
		usage()
		os.Exit(1)
		return
	}
	if "-c" != os.Args[1] {
		usage()
		os.Exit(1)
		return
	}

	filename := os.Args[2]
	f, err := os.Open(filename)
	if nil != err {
		log.Fatal(err)
		return
	}

	configFile, err := ioutil.ReadAll(f)
	if nil != err {
		log.Fatal(err)
		return
	}

	config := &watchdog.Config{}
	err = json.Unmarshal(configFile, config)
	if nil != err {
		log.Fatal(err)
		return
	}

	//fmt.Printf("%#v\n", config)

	done := make(chan struct{}, 1)

	allWebhooks := make(map[string]watchdog.Webhook)

	for i := range config.Webhooks {
		h := config.Webhooks[i]
		allWebhooks[h.Name] = h
	}

	logQueue := make(chan string, 10)
	go logger(logQueue)
	for i := range config.Watches {
		c := config.Watches[i]
		logQueue <- fmt.Sprintf("Watching '%s'", c.Name)
		go func(c watchdog.ConfigWatch) {
			d := watchdog.New(&watchdog.Dog{
				Name:        c.Name,
				CheckURL:    c.URL,
				Keywords:    c.Keywords,
				Recover:     c.RecoverScript,
				Webhooks:    c.Webhooks,
				AllWebhooks: allWebhooks,
				Logger:      logQueue,
			})
			d.Watch()
		}(config.Watches[i])
	}

	if 0 == len(config.Watches) {
		log.Fatal("Nothing to watch")
		return
	}

	<-done
}

// This is so that the log messages don't trample
// over each other when they happen simultaneously.
func logger(msgs chan string) {
	for {
		msg := <-msgs
		log.Println(msg)
	}
}
