package cmd

import (
	"io"
	"log"
	"os"
	"os/exec"
)

// Cmd Overloads the exec.Cmd class to save the full command
// and adds custom input/output pipes
type Cmd struct {
	fullCommand	string
	*exec.Cmd
	inReader	io.Reader
	InWriter	io.Writer
	OutReader	io.Reader
	outWriter	io.Writer
}

// Start creates a new cmd object with given arguments, runs and then returns it
func Start(args string) (*Cmd, io.Reader, io.Writer) {
	ir, iw := io.Pipe()
	or, ow := io.Pipe()
	c := Cmd {
		"vde_plug " + args,
		exec.Command("vde_plug", args),
		ir,
		iw,
		or,
		ow,
	}
	c.Stdout = c.outWriter
	c.Stdin = c.inReader
	c.Stderr = os.Stderr
	err := c.Start()
	if err != nil {
		log.Printf("%s failed with %s\n", c.fullCommand, err)
	}
	return &c, c.OutReader, c.InWriter
}

// WaitH runs Cmd.Wait() and catches the possible error
func (c *Cmd) WaitH() {
	err := c.Wait()
	if err != nil {
		log.Printf("%s failed with %s\n", c.fullCommand, err)
	}
}

const (
	Out = ">> "	// Prefix for traffic from VM
	In = "<< "	// Prefix for traffic to VM
)