//go:build windows
// +build windows

package cm

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

	"be.ems/lib/log"
)

func ExecCmd(command string) error {
	log.Debug("Exec command:", command)

	cmd := exec.Command("cmd", "/C", command)
	out, err := cmd.CombinedOutput()
	log.Tracef("Exec output: %v", string(out))
	if err != nil {
		log.Error("exe cmd error: ", err)
		return err
	}
	/*
		if err := cmd.Start(); err != nil {
			log.Error("Start error: ", err)
			return err
		}
		if err := cmd.Wait(); err != nil {
			log.Error("Wait error: ", err)
			return err
		}
	*/
	return nil
}

func ExecOsCmd(command, os string) error {
	log.Debugf("Exec %s command:%s", os, command)

	var cmd *exec.Cmd
	switch os {
	case "Linux":
		cmd = exec.Command(command)
	case "Windows":
		cmd = exec.Command("cmd", "/C", command)
	}

	out, err := cmd.CombinedOutput()
	log.Tracef("Exec output: %v", string(out))
	if err != nil {
		log.Error("exe cmd error: ", err)
		return err
	}
	return nil
}

func StartSSHCmdWithTimeout(duration int, sshHost, cmdStr string) error {
	timeout := time.Duration(duration) * time.Second
	ctx, cancel := context.WithTimeout(context.Background(), timeout) // 设置超时
	defer cancel()
	cmd := exec.CommandContext(ctx, "ssh", sshHost, cmdStr)
	var stdout, stderr bytes.Buffer
	cmd.Stdout = &stdout
	cmd.Stderr = &stderr
	err := cmd.Start()
	if err != nil {
		return err
	}
	return nil
}

func RunSSHCmd(sshHost, cmdStr string) error {
	cmd := exec.Command("ssh", sshHost, cmdStr)
	var stdout, stderr bytes.Buffer
	cmd.Stdout = &stdout
	cmd.Stderr = &stderr
	err := cmd.Run()
	if err != nil {
		return err
	}
	return nil
}
