package lib

import (
	"os"
)

// OpenOutboundHalfPipe returns a handle to a process. Writing to that handle
// writes to the process' stdin. The process' stdout and stderr are the current
// process' stdout and stderr.
//
// This is for pipe-redirection in the Miller put/filter DSL.
//
// Note I am not using os.exec.Cmd which is billed as being simpler than using
// os.StartProcess. It may indeed be simpler when you want to handle the
// subprocess' stdin/stdout/stderr all three within the parent process.  Here I
// found it much easier to use os.StartProcess to let the stdout/stderr run
// free.

func OpenOutboundHalfPipe(commandString string) (*os.File, error) {
	readPipe, writePipe, err := os.Pipe()

	var procAttr os.ProcAttr
	procAttr.Files = []*os.File{
		readPipe,
		os.Stdout,
		os.Stderr,
	}

	args := []string{
		"/bin/sh",
		"-c",
		commandString,
	}

	process, err := os.StartProcess(args[0], args, &procAttr)
	if err != nil {
		return nil, err
	}

	go process.Wait()

	return writePipe, nil
}
