package cmd

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

// 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
}

// New creates a new cmd object with given arguments and returns it
func New(name string, args string) *cmd{
	ir, iw := io.Pipe()
	or, ow := io.Pipe()
	c := cmd {
		name + " " + args,
		exec.Command(name, args),
		ir,
		iw,
		or,
		ow,
	}
	c.Stdout = c.outWriter
	c.Stdin = c.inReader
	c.Stderr = os.Stderr
	return &c
}

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

// 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
)