//go:build !windows

package deploy

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

	"crypto-miner-agent/config"
)

// launchProcessGuard spawns a detached shell loop that watches for the installed
// miner and restarts it on crash (Unix — Linux + macOS).
func launchProcessGuard(cfg config.RuntimeConfig) {
	installDir, err := cfg.InstallDirectory()
	if err != nil {
		return
	}
	bin := filepath.Join(installDir, BinaryName(cfg))
	procName := strings.TrimSuffix(BinaryName(cfg), "")

	// sh one-liner: loop forever, sleep 60 s, pgrep by binary name, restart if missing.
	script := fmt.Sprintf(
		`while true; do sleep 60; pgrep -x '%s' >/dev/null 2>&1 || ([ -x '%s' ] && nohup '%s' --run >/dev/null 2>&1 &); done`,
		procName, bin, bin,
	)
	cmd := exec.Command("sh", "-c", script)
	_ = cmd.Start()
}
