package main

import (
	"io"
	"os"
	"syscall"

	"encoding/json"
	"io/ioutil"
	"os/exec"

	log "github.com/AcalephStorage/consul-alerts/Godeps/_workspace/src/github.com/Sirupsen/logrus"
)

func runWatcher(consulAddr, datacenter, alertAddr, logLevel, consulAclToken, watchType string) {
	consulAlert := os.Args[0]
	cmd := exec.Command(
		"consul", "watch",
		"-http-addr", consulAddr,
		"-datacenter", datacenter,
		"-token", consulAclToken,
		"-type", watchType,
		consulAlert, "watch", watchType, "--alert-addr", alertAddr, "--log-level", logLevel)
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr

	if err := cmd.Run(); err != nil {
		var exitCode int
		switch err.(type) {
		case *exec.ExitError:
			exitError, _ := err.(*exec.ExitError)
			status, _ := exitError.Sys().(syscall.WaitStatus)
			exitCode = status.ExitStatus()
			log.Println("Shutting down watcher --> Exit Code: ", exitCode)
		case *exec.Error:
			exitCode = 1
			log.Println("Shutting down watcher --> Something went wrong running consul watch: ", err.Error())
		default:
			exitCode = 127
			log.Println("Shutting down watcher --> Unknown error: ", err.Error())
		}
		os.Exit(exitCode)
	} else {
		log.Printf("Execution complete.")
	}
}

func toWatchObject(reader io.Reader, v interface{}) {
	data, err := ioutil.ReadAll(reader)
	if err != nil {
		log.Println("stdin read error: ", err)
		// todo: what to do when can't read?
	}
	err = json.Unmarshal(data, v)
	if err != nil {
		log.Println("json unmarshall error: ", err)
		// todo: what if we can't serialise?
	}
}
