package winpwn

import (
	"fmt"
	"os/exec"
	"path/filepath"
)

// Spawn launches a local target process and wires up its stdin/stdout as
// a Tube, the Go analogue of pwntools' process().
func Spawn(target string) (*Tube, error) {
	// Resolve to an absolute path, e.g. "bof_win.c.exe" -> "C:\...\bof_win.c.exe".
	if absTarget, err := filepath.Abs(target); err == nil {
		target = absTarget
	}

	cmd := exec.Command(target)

	stdin, err := cmd.StdinPipe()
	if err != nil {
		return nil, fmt.Errorf("StdinPipe: %w", err)
	}

	stdout, err := cmd.StdoutPipe()
	if err != nil {
		return nil, fmt.Errorf("StdoutPipe: %w", err)
	}

	if err := cmd.Start(); err != nil {
		return nil, fmt.Errorf("Start: %w", err)
	}

	return newTube(cmd, nil, stdin, stdout), nil
}
