//go:build linux

package bridge

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

	"tailscale.com/client/local"
)

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

	if !shouldIgnoreLoginCheckPrefsError(&local.AccessDeniedError{}) {
		t.Fatal("shouldIgnoreLoginCheckPrefsError(access denied) = false, want true")
	}
}

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

	if shouldIgnoreLoginCheckPrefsError(errors.New("boom")) {
		t.Fatal("shouldIgnoreLoginCheckPrefsError(non-access-denied) = true, want false")
	}
}

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

	dir := t.TempDir()
	bridgeProgram := filepath.Join(dir, "mirage-qt")
	sibling := filepath.Join(dir, "mirage")
	if err := os.WriteFile(sibling, []byte("#!/bin/sh\n"), 0o755); err != nil {
		t.Fatalf("WriteFile: %v", err)
	}

	got := cliExecutablePathWithBridge("", bridgeProgram, func(string) (string, error) {
		return "", errors.New("not found")
	})
	want := sibling
	if got != want {
		t.Fatalf("cliExecutablePathWithBridge() = %q, want %q", got, want)
	}
}

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

	name, args, err := operatorGrantCommand("/usr/bin/mirage", "alice")
	if err != nil {
		t.Fatalf("operatorGrantCommand() error = %v", err)
	}
	if name != "pkexec" {
		t.Fatalf("command = %q, want pkexec", name)
	}
	want := []string{"/usr/bin/mirage", "set", "--operator=alice"}
	if len(args) != len(want) {
		t.Fatalf("args len = %d, want %d (%v)", len(args), len(want), args)
	}
	for i := range want {
		if args[i] != want[i] {
			t.Fatalf("args[%d] = %q, want %q (full=%v)", i, args[i], want[i], args)
		}
	}
}
