package infra

import (
	"os/exec"
)

// SSHExec ejecuta un comando en el host remoto via SSH y retorna stdout, stderr y exit code.
func SSHExec(conn SSHConn, command string) (string, string, int, error) {
	args := conn.sshArgs()
	args = append(args, "-o", "BatchMode=yes")
	args = append(args, conn.destination(), command)

	cmd := exec.Command("ssh", args...)
	var stdout, stderr []byte
	cmd.Stdout = writerFunc(func(p []byte) (int, error) {
		stdout = append(stdout, p...)
		return len(p), nil
	})
	cmd.Stderr = writerFunc(func(p []byte) (int, error) {
		stderr = append(stderr, p...)
		return len(p), nil
	})

	err := cmd.Run()
	exitCode := 0
	if err != nil {
		if exitErr, ok := err.(*exec.ExitError); ok {
			exitCode = exitErr.ExitCode()
		} else {
			return "", "", -1, err
		}
	}
	return string(stdout), string(stderr), exitCode, nil
}

// writerFunc adapta una funcion a io.Writer.
type writerFunc func([]byte) (int, error)

func (f writerFunc) Write(p []byte) (int, error) { return f(p) }
