package main

import (
	"bytes"
	"context"
	"fmt"
	"os/exec"
	"time"
)

// localExecSSHCommand 执行本地命令并返回命令输出和错误信息
func localExecSSHCommand(command string, timeout time.Duration) (string, error) {
	// 使用上下文设置超时时间
	ctx, cancel := context.WithTimeout(context.Background(), timeout)
	defer cancel()

	// 创建命令实例
	cmd := exec.CommandContext(ctx, "sh", "-c", command)

	// 捕获命令输出
	var stdout, stderr bytes.Buffer
	cmd.Stdout = &stdout
	cmd.Stderr = &stderr

	// 执行命令
	err := cmd.Run()
	if ctx.Err() == context.DeadlineExceeded {
		return "", fmt.Errorf("command timeout exceeded: %v", command)
	}
	if err != nil {
		return "", fmt.Errorf("command failed: %v, stderr: %s", err, stderr.String())
	}

	return stdout.String(), nil
}
