package tenants

// Fakes for the production aws/kubectl shell-outs: real subprocesses running
// canned /bin/sh scripts, installed by prepending a temp dir to PATH so the
// production executable names resolve to them.

import (
	"os"
	"path/filepath"
	"strings"
	"testing"

	"github.com/stretchr/testify/assert"
)

// putOnPATH writes an executable /bin/sh script named bin into a fresh dir
// prepended to PATH, so subprocess lookups of bin run it for the test's
// duration.
func putOnPATH(t *testing.T, bin, body string) {
	t.Helper()
	dir := t.TempDir()
	path := filepath.Join(dir, bin)
	assert.NoError(t, os.WriteFile(path, []byte("#!/bin/sh\n"+body), 0o755))
	t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH"))
}

// shellQuote single-quotes s for /bin/sh. Test-script inputs (tempdir paths)
// never contain quotes.
func shellQuote(s string) string {
	return "'" + s + "'"
}

// recordArgs returns a script prefix that appends one argument per line to
// file, preserving embedded spaces within a single argument.
func recordArgs(file string) string {
	return "printf '%s\\n' \"$@\" >> " + shellQuote(file) + "\n"
}

// readArgs reads back arguments recorded by recordArgs.
func readArgs(t *testing.T, file string) []string {
	t.Helper()
	data, err := os.ReadFile(file)
	assert.NoError(t, err)
	lines := strings.Split(strings.TrimSuffix(string(data), "\n"), "\n")
	if len(lines) == 1 && lines[0] == "" {
		return nil
	}
	return lines
}
