package daemon

import (
	"os"
	"os/exec"
	"syscall"
	"time"

	"github.com/inconshreveable/log15"
)

type DaemonState int

const (
	DaemonInit DaemonState = iota
	DaemonStart
	DaemonStop
)

type Daemon struct {
	path     string
	progName string
	args     []string
	state    DaemonState

	cmd *exec.Cmd
}

func NewDaemon(path, progName string, args ...string) *Daemon {
	d := &Daemon{
		path:     path,
		progName: progName,
		args:     args,
		state:    DaemonInit,
	}
	return d
}

func (d *Daemon) CMDStop() {
	log15.Info(d.progName + " CMDStop")
	d.cmd.Process.Kill()
	d.state = DaemonStop
}

func (d *Daemon) CMDStart() {
	log15.Info(d.progName + " CMDStart")
	d.state = DaemonStart
	go func() {
		log15.Info(d.progName + " 守护协程 启动")
		for d.state == DaemonStart {
			os.Chdir(d.path)
			d.cmd = exec.Command(d.progName, d.args...)
			d.cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true}
			err := d.cmd.Start()
			if err != nil {
				log15.Error(d.progName+" 启动命令失败", "err", err)
				time.Sleep(time.Second * 5)
				continue
			} else {
				log15.Info(d.progName + " 进程启动")
			}
			err = d.cmd.Wait()
			log15.Info(d.progName+" 进程退出", "err", err)
			time.Sleep(time.Second * 1)
		}
		log15.Info(d.progName + " 守护协程 退出")
	}()
}