package guestconfig

import (
	"strings"
	"testing"
)

func TestBuilderRenderFSTabReplacesManagedTargetsAndDropsLegacyMounts(t *testing.T) {
	builder := NewBuilder()
	builder.DropMountTarget("/home")
	builder.DropMountTarget("/var")
	builder.AddMount(MountSpec{
		Source:  "/dev/vdb",
		Target:  "/root",
		FSType:  "ext4",
		Options: []string{"defaults"},
		Dump:    0,
		Pass:    2,
	})
	builder.AddMount(MountSpec{
		Source:  "tmpfs",
		Target:  "/run",
		FSType:  "tmpfs",
		Options: []string{"defaults", "nodev", "nosuid", "mode=0755"},
	})
	builder.AddMount(MountSpec{
		Source:  "tmpfs",
		Target:  "/tmp",
		FSType:  "tmpfs",
		Options: []string{"defaults", "nodev", "nosuid", "mode=1777"},
	})

	input := strings.Join([]string{
		"/dev/vdb /home ext4 defaults 0 2",
		"/dev/vdc /var ext4 defaults 0 2",
		"/dev/vdb /root ext4 defaults 0 2",
		"tmpfs /run tmpfs defaults,nodev,nosuid,mode=0700 0 0",
		"",
	}, "\n")

	got := builder.RenderFSTab(input)

	if strings.Contains(got, "/home") {
		t.Fatalf("RenderFSTab() kept /home mount: %q", got)
	}
	if strings.Contains(got, "/var") {
		t.Fatalf("RenderFSTab() kept /var mount: %q", got)
	}
	if strings.Count(got, "/dev/vdb /root") != 1 {
		t.Fatalf("RenderFSTab() duplicated /root mount: %q", got)
	}
	if !strings.Contains(got, "tmpfs /run tmpfs defaults,nodev,nosuid,mode=0755 0 0") {
		t.Fatalf("RenderFSTab() missing rendered /run mount: %q", got)
	}
	if !strings.Contains(got, "tmpfs /tmp tmpfs defaults,nodev,nosuid,mode=1777 0 0") {
		t.Fatalf("RenderFSTab() missing rendered /tmp mount: %q", got)
	}
}

func TestBuilderFilesReturnsCopies(t *testing.T) {
	builder := NewBuilder()
	builder.WriteFile("/etc/hostname", []byte("devbox\n"))

	files := builder.Files()
	files["/etc/hostname"][0] = 'x'

	again := builder.Files()
	if string(again["/etc/hostname"]) != "devbox\n" {
		t.Fatalf("Files() returned aliasing data: %q", string(again["/etc/hostname"]))
	}
}
