package utils

import (
	"bufio"
	"fmt"
	"os/exec"
)

func RunCommandWithStdoutPipe(workdir, progName string, args ...string) error {
	cmd := exec.Command(progName, args...)
	cmd.Dir = workdir
	out, err := cmd.StdoutPipe()
	if err != nil {
		return err
	}

	scanner := bufio.NewScanner(out)
	go func() {
		counter := 0
		for scanner.Scan() {
			if counter > 10 {
				// Swallow the output
				if counter%50 == 0 {
					fmt.Printf("output %d lines in total.\n", counter)
				}
				counter++
				continue
			}
			PrintOutput("", scanner.Bytes())
			counter++
		}
	}()

	err = cmd.Start()
	if err != nil {
		return err
	}

	err = cmd.Wait()
	if err != nil {
		return err
	}

	return nil
}
