package bootstrap

import (
	log "github.com/cihub/seelog"
	"net"
	"os"
	"strings"
)

const FILE_SERVER string = "/var/run/of_server"

var fd net.Conn

func handleShell(stop chan bool) {

	//os.Stdout.Close()
	//os.Stderr.Close()
	//os.Stdin.Close()

	if fi, _ := os.Stat(FILE_SERVER); fi != nil {
		os.Remove(FILE_SERVER)
	}

	l, err := net.ListenUnix("unix", &net.UnixAddr{Name: FILE_SERVER, Net: "unix"})
	if err != nil {
		log.Error(err.Error())
		return
	}
	defer func() {
		l.Close()
		os.Remove(FILE_SERVER)
	}()

	for {
		fd, err = l.Accept()
		if err != nil {
			log.Error(err)
			return
		}

		buf := make([]byte, 1024)
		nr, err := fd.Read(buf)
		if err != nil {
			return
		}

		data := string(buf[0:nr])
		switch strings.ToUpper(data) {
		case "STOP":
			if fi, _ := os.Stat(FILE_SERVER); fi != nil {
				os.Remove(FILE_SERVER)
			}
			stop <- true
		case "STATUS":
			fd.Write(status())
		default:
		}

		fd.Close()
	}
}

func stopHandleShell() {
	log.Info("Shell Handler stopped.")

	if fi, _ := os.Stat(FILE_SERVER); fi != nil {
		os.Remove(FILE_SERVER)
	}
	if fd != nil {
		fd.Close()
	}
}

func status() []byte {
	return []byte("STATUS OK\n")
}
