//go:build !windows

package shim

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

// End-to-end reproduction of Yosif's failure: a generated shim must work when
// PATH is missing the system dirs (no /usr/bin, no /bin), where the old
// dirname-based form aborted with "line 5: dirname: command not found" and then
// "no real git on PATH". With the builtin ${0%/*} form the shim resolves and
// execs the real binary instead of dying.
func TestShimSurvivesHostilePATH(t *testing.T) {
	shimDir := t.TempDir()
	realBin := t.TempDir()

	// A real (non-shim) git that just echoes, placed off any system path.
	realGit := filepath.Join(realBin, "git")
	if err := os.WriteFile(realGit, []byte("#!/bin/sh\necho FAKEGIT \"$@\"\n"), 0o755); err != nil {
		t.Fatal(err)
	}
	// The managed shim, generated by the real template.
	shimPath := filepath.Join(shimDir, "git")
	if err := os.WriteFile(shimPath, []byte(shimScript("git", "/nonexistent/ctx-wire")), 0o755); err != nil {
		t.Fatal(err)
	}

	cmd := exec.Command(shimPath, "--version")
	// Hostile PATH: only the shim dir and the real-bin dir, no /usr/bin or /bin.
	// No agent ancestor, so the shim must passthrough-exec the real binary.
	cmd.Env = []string{"PATH=" + shimDir + string(os.PathListSeparator) + realBin}
	out, err := cmd.CombinedOutput()
	got := string(out)

	if strings.Contains(got, "dirname") {
		t.Errorf("shim still hit a dirname failure on a stripped PATH:\n%s", got)
	}
	if strings.Contains(got, "no real") {
		t.Errorf("shim failed to resolve the real git on a stripped PATH:\n%s", got)
	}
	if !strings.Contains(got, "FAKEGIT --version") {
		t.Errorf("shim did not exec the real git (err=%v):\n%s", err, got)
	}
}
