package main

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

type runCommandType func(args []string) ([]string, error)

func runCommand(args []string) ([]string, error) {
	cmd := exec.Command(args[0], args[1:]...)
	cmd.Dir = "/" // to not be affected if the current directory is removed
	out, err := cmd.CombinedOutput()
	lines := strings.Split(string(out), "\n")
	if err != nil {
		return lines, fmt.Errorf("%q failed: %w", strings.Join(args, " "), err)
	}

	lines, err = readLines(bytes.NewReader(out))
	if err != nil {
		return lines, fmt.Errorf("failed to read the output of %q: %w", args, err)
	}

	return lines, nil
}

func readLines(r io.Reader) ([]string, error) {
	var lines []string
	scanner := bufio.NewScanner(r)
	for scanner.Scan() {
		lines = append(lines, scanner.Text())
	}
	if err := scanner.Err(); err != nil {
		return nil, err
	}
	return lines, nil
}
