package container

import (
	"strings"
	"testing"

	"hakurei.app/fhs"
)

func TestEscapeBinfmt(t *testing.T) {
	t.Parallel()

	testCases := []struct {
		name  string
		magic string
		want  string
	}{
		{"packed DOS applications", "\x0eDEX", "\x0eDEX"},

		{"riscv64 magic",
			"\x7fELF\x02\x01\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00\xf3\x00",
			"\x7fELF\x02\x01\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\x02\\x00\xf3\\x00"},
		{"riscv64 mask",
			"\xff\xff\xff\xff\xff\xff\xff\x00\xff\xff\xff\xff\xff\xff\xff\xff\xfe\xff\xff\xff",
			"\xff\xff\xff\xff\xff\xff\xff\\x00\xff\xff\xff\xff\xff\xff\xff\xff\xfe\xff\xff\xff"},
	}
	for _, tc := range testCases {
		t.Run(tc.name, func(t *testing.T) {
			t.Parallel()

			got := escapeBinfmt(new(strings.Builder), tc.magic)
			if got != tc.want {
				t.Errorf("escapeBinfmt: %q, want %q", got, tc.want)
			}
		})
	}
}

func TestBinfmtEntry(t *testing.T) {
	t.Parallel()

	testCases := []struct {
		name  string
		e     BinfmtEntry
		valid bool
	}{
		{"zero", BinfmtEntry{}, false},
		{"large offset", BinfmtEntry{Offset: 128}, false},
		{"long magic", BinfmtEntry{Magic: strings.Repeat("\x00", 128)}, false},
		{"long mask", BinfmtEntry{Mask: strings.Repeat("\x00", 128)}, false},
		{"valid", BinfmtEntry{Interpreter: fhs.AbsRoot}, true},
	}
	for _, tc := range testCases {
		t.Run(tc.name, func(t *testing.T) {
			t.Parallel()

			if tc.e.Valid() != tc.valid {
				t.Errorf("Valid: %v", !tc.valid)
			}
		})
	}
}
