package tools

import (
	"bytes"
	"io"
	"os"
	"os/exec"
	"strings"
)

func execc(stdin io.Reader, stdout, stderr io.Writer, command string, args []string, env []string) error {
	c := strings.Split(command, " ")
	cmd := exec.Command(c[0], append(c[1:], args...)...)
	cmd.Env = append(os.Environ(), env...)
	cmd.Stdin = stdin
	cmd.Stdout = stdout
	cmd.Stderr = stderr
	return cmd.Run()
}

func execCommandDir(out io.Writer, commandDir string, env ...string) error {
	stderr := bytes.NewBuffer(nil)
	if err := execc(nil, out, stderr, "go run", []string{commandDir}, env); err != nil {
		io.Copy(os.Stderr, stderr)
		return err
	}

	return nil
}

func execInternal(command string, args ...string) error {
	stdout := bytes.NewBuffer(nil)
	stderr := bytes.NewBuffer(nil)
	if err := execc(nil, stdout, stderr, command, args, nil); err != nil {
		io.Copy(os.Stderr, stdout)
		io.Copy(os.Stderr, stderr)
		return err
	}

	return nil
}

func execTransparent(command string, args ...string) error {
	return execc(os.Stdin, os.Stdout, os.Stderr, command, args, nil)
}
