package image

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

	"metis/pkg/inject"
)

func TestWriteExt4Files(t *testing.T) {
	if _, err := exec.LookPath("mkfs.ext4"); err != nil {
		t.Skip("mkfs.ext4 not available")
	}
	if _, err := exec.LookPath("debugfs"); err != nil {
		t.Skip("debugfs not available")
	}

	workDir := t.TempDir()
	fsPath := filepath.Join(workDir, "root.ext4")
	f, err := os.Create(fsPath)
	if err != nil {
		t.Fatal(err)
	}
	if err := f.Truncate(32 * 1024 * 1024); err != nil {
		t.Fatal(err)
	}
	if err := f.Close(); err != nil {
		t.Fatal(err)
	}

	cmd := exec.Command("mkfs.ext4", "-F", fsPath)
	if out, err := cmd.CombinedOutput(); err != nil {
		t.Fatalf("mkfs.ext4: %v: %s", err, string(out))
	}

	files := []inject.FileSpec{
		{
			Path:    "etc/metis/firstboot.env",
			Content: []byte("METIS_HOSTNAME='titan-13'\n"),
			Mode:    0o600,
			RootFS:  true,
		},
		{
			Path:    "usr/local/sbin/test.sh",
			Content: []byte("#!/usr/bin/env bash\nexit 0\n"),
			Mode:    0o755,
			RootFS:  true,
		},
	}
	if err := writeExt4Files(fsPath, files); err != nil {
		t.Fatalf("writeExt4Files: %v", err)
	}
}

func TestParentDirs(t *testing.T) {
	got := parentDirs("etc/metis/firstboot.env")
	want := []string{"/etc", "/etc/metis"}
	if len(got) != len(want) {
		t.Fatalf("parentDirs length mismatch: got %v want %v", got, want)
	}
	for i := range want {
		if got[i] != want[i] {
			t.Fatalf("parentDirs[%d] = %q want %q", i, got[i], want[i])
		}
	}
}
