package mount

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

func TestSetupAndTeardownUseHelperCommands(t *testing.T) {
	scripts := fakeCommandDir(t)
	t.Setenv("PATH", scripts+string(os.PathListSeparator)+os.Getenv("PATH"))
	image := filepath.Join(t.TempDir(), "disk.img")
	if err := os.WriteFile(image, []byte("image"), 0o644); err != nil {
		t.Fatal(err)
	}

	m, err := Setup(image)
	if err != nil {
		t.Fatalf("Setup: %v", err)
	}
	if m.LoopDevice != "/dev/loop9" {
		t.Fatalf("loop device = %q", m.LoopDevice)
	}
	if !strings.Contains(m.BootPath, "metis-boot-") || !strings.Contains(m.RootPath, "metis-root-") {
		t.Fatalf("unexpected mount paths: %+v", m)
	}
	if err := Teardown(m); err != nil {
		t.Fatalf("Teardown: %v", err)
	}
}

func TestPartitionPathFallsBackToNumberSuffix(t *testing.T) {
	if got := partitionPath("/dev/loop0", 2); got != "/dev/loop02" {
		t.Fatalf("partitionPath = %q", got)
	}
}

func TestTeardownNilAndDirectDeviceSetup(t *testing.T) {
	if err := Teardown(nil); err != nil {
		t.Fatalf("Teardown(nil): %v", err)
	}
	scripts := fakeCommandDir(t)
	t.Setenv("PATH", scripts+string(os.PathListSeparator)+os.Getenv("PATH"))
	if _, err := Setup("/dev/loop9"); err != nil {
		t.Fatalf("Setup direct device: %v", err)
	}
}

func fakeCommandDir(t *testing.T) string {
	t.Helper()
	dir := t.TempDir()
	write := func(name, body string) {
		path := filepath.Join(dir, name)
		if err := os.WriteFile(path, []byte("#!/usr/bin/env bash\nset -eu\n"+body+"\n"), 0o755); err != nil {
			t.Fatalf("write %s: %v", name, err)
		}
	}
	write("losetup", `if [[ "${1:-}" == "-Pf" && "${2:-}" == "--show" ]]; then
  printf '/dev/loop9\n'
  exit 0
fi
exit 0`)
	write("mount", `exit 0`)
	write("umount", `exit 0`)
	return dir
}
