package shell

import (
	"os"
	"os/exec"
)

func (d DeviceShell) RunSync(command string, args ...string) ([]byte, error) {
	fc := append([]string{"-s", d.Connection().Device().Serial(), "shell", command}, args...)
	return exec.Command(d.Connection().Adb().BinPath(), fc...).CombinedOutput()
}

func (d DeviceShell) StartAsync(command string, args ...string) (*exec.Cmd, error) {
	fc := append([]string{"-s", d.connection.Device().Serial(), "shell", command}, args...)
	cmd := exec.Command(d.Connection().Adb().BinPath(), fc...)
	return cmd, cmd.Start()
}

func (d DeviceShell) StopAsync(cmd *exec.Cmd) error {
	if err := cmd.Process.Signal(os.Interrupt); err != nil {
		return err
	}
	if err := cmd.Process.Release(); err == nil || err.Error() == "signal: interrupt" {
		return nil
	} else {
		return err
	}
}
