package proc

import (
	"os"
	"syscall"

	//"fmt"
	//"bufio"
	"os/exec"
	//"runtime"
	//"syscall"

	"log"

	"gitlab.com/olanguage/olang/pid"
)

type Proc struct {
	Name    string
	Command string
	Arg     string
	Process *os.Process
}

type Data struct {
	output []byte
	error  error
	exec   *exec.Cmd
}

func New(name string, command string, arg string) *Proc {
	process := &Proc{
		Command: command,
		Arg:     arg,
		Name:    name,
	}
	return process
}

func (p *Proc) RunCommand(ch chan<- Data) {
	//cmd := exec.Command(p.Command, p.Arg, "&")
	cmd := exec.Command("/bin/bash", "-c", "nohup "+p.Command+" "+p.Arg+" > /dev/null 2>&1 &")
	data, err := cmd.CombinedOutput()
	ch <- Data{
		error:  err,
		output: data,
		exec:   cmd,
	}
}

func (p *Proc) Execute() {

	if _, err := os.Stat(".oproc"); os.IsNotExist(err) {
		os.Mkdir(".oproc", 0777)
	}

	id, _ := pid.GetValue(".oproc/" + p.Name + ".pid")
	if id != 0 {
		log.Printf("Proc Running: %d\n", id)
		os.Exit(1)
	}

	c := make(chan Data)

	go p.RunCommand(c)

	res := <-c

	pf := pid.New(int64(res.exec.Process.Pid))
	pf.Create(".oproc/" + p.Name + ".pid")
	p.Process = res.exec.Process

	log.Printf("Running Proc: %d\n", res.exec.Process.Pid)

	log.Printf("Running Command: %s %s\n", p.Command, p.Arg)
}

func (p *Proc) Kill() bool {
	if _, err := os.Stat(".oproc"); os.IsNotExist(err) {
		log.Printf("Pid folder not found!")
		os.Exit(0)
	}

	id, err := pid.GetValue(".oproc/" + p.Name + ".pid")
	if err != nil {
		log.Printf("Process not found.\n")
		os.Exit(1)
	}

	log.Printf("Process stoped: %d\n", id)
	syscall.Kill(id, syscall.SIGTERM)
	os.Remove(".oproc/" + p.Name + ".pid")

	return true
}
