//go:build linux

package startup

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

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

	dir := t.TempDir()
	c := Controller{
		ConfigHome: dir,
		ExecPath:   func() (string, error) { return "/opt/mirage/mirage-qt-ui", nil },
	}

	enabled, err := c.Enabled()
	if err != nil {
		t.Fatalf("Enabled() before create error = %v", err)
	}
	if enabled {
		t.Fatal("Enabled() before create = true, want false")
	}

	if err := c.SetEnabled(true); err != nil {
		t.Fatalf("SetEnabled(true) error = %v", err)
	}

	enabled, err = c.Enabled()
	if err != nil {
		t.Fatalf("Enabled() after create error = %v", err)
	}
	if !enabled {
		t.Fatal("Enabled() after create = false, want true")
	}
}

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

	dir := t.TempDir()
	const exe = "/opt/mirage/bin/mirage-qt-ui"
	c := Controller{
		ConfigHome: dir,
		ExecPath:   func() (string, error) { return exe, nil },
	}

	if err := c.SetEnabled(true); err != nil {
		t.Fatalf("SetEnabled(true) error = %v", err)
	}

	data, err := os.ReadFile(filepath.Join(dir, "autostart", DesktopFileName))
	if err != nil {
		t.Fatalf("ReadFile(desktop): %v", err)
	}
	text := string(data)
	if !strings.Contains(text, "Name=Mirage") {
		t.Fatalf("desktop entry missing Name=Mirage: %q", text)
	}
	if !strings.Contains(text, "Exec="+exe) {
		t.Fatalf("desktop entry missing Exec path: %q", text)
	}
}

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

	dir := t.TempDir()
	c := Controller{
		ConfigHome: dir,
		ExecPath:   func() (string, error) { return "/opt/mirage/mirage-qt-ui", nil },
	}

	if err := c.SetEnabled(true); err != nil {
		t.Fatalf("SetEnabled(true) error = %v", err)
	}
	if err := c.SetEnabled(false); err != nil {
		t.Fatalf("SetEnabled(false) error = %v", err)
	}

	if _, err := os.Stat(filepath.Join(dir, "autostart", DesktopFileName)); !os.IsNotExist(err) {
		t.Fatalf("desktop entry still exists, err = %v", err)
	}
}
