package executil

import (
	"bytes"
	"io"
	"log"
	"os"
	"os/exec"
	"strings"
)

const ScriptsRoot = "/opt/zlh-agent/scripts"

func RunScript(path string) error {
	cmd := exec.Command("/bin/bash", path)
	var buf bytes.Buffer
	cmd.Stdout = io.MultiWriter(os.Stdout, &buf)
	cmd.Stderr = io.MultiWriter(os.Stderr, &buf)
	log.Printf("[provision] action=run_script path=%s", path)
	if err := cmd.Run(); err != nil {
		log.Printf("[provision] action=run_script status=failed path=%s err=%v", path, err)
		for _, line := range tailLogLines(buf.String(), 10) {
			log.Printf("[provision] path=%s output=%s", path, line)
		}
		return err
	}
	log.Printf("[provision] action=run_script status=ok path=%s", path)
	return nil
}

func tailLogLines(raw string, max int) []string {
	lines := strings.Split(strings.ReplaceAll(raw, "\r\n", "\n"), "\n")
	out := make([]string, 0, max)
	for _, line := range lines {
		line = strings.TrimSpace(line)
		if line == "" {
			continue
		}
		out = append(out, line)
	}
	if len(out) <= max {
		return out
	}
	return out[len(out)-max:]
}
