# Keyring Package Implementation Summary

## Overview
Implemented `pkg/keyring` package for Linux sudo authentication in Web UI mode using `github.com/99designs/keyring` for multi-backend support.

## Files Created

### 1. `pkg/keyring/keyring.go` (462 lines)
Main keyring package with:
- **Backend Types**: SecretService, KWallet, Pass, File, None
- **Status Struct**: Comprehensive status information (AvailableBackends, ActiveBackend, DaemonRunning, InstallHint, Distro, DesktopEnv, HasPassword, Platform)
- **Core Functions**:
  - `DetectStatus()` - Detects available backends and current environment
  - `Open()` - Opens keyring with backends in priority order
  - `StorePassword(password string) error` - Stores sudo password
  - `GetPassword() (string, error)` - Retrieves sudo password
  - `HasPassword() bool` - Checks if password is stored
  - `DeletePassword() error` - Removes stored password
  - `Backend() BackendType` - Returns active backend type
- **Helper Functions**:
  - `detectDistro()` - Detects Linux distro from /etc/os-release
  - `detectDesktopEnvironment()` - Detects DE from XDG_CURRENT_DESKTOP
  - `generateInstallHint(distro, de string)` - Generates install command
  - `detectAvailableBackends()` - Checks which backends are available
  - `checkDaemonRunning(backend BackendType)` - Checks if daemon is running
  - `checkCommandExists(cmd string)` - Checks if command exists in PATH
  - `checkProcessRunning(name string)` - Checks if process is running

### 2. `pkg/keyring/check.go` (193 lines)
Dependency checking and validation:
- **Error Variables**:
  - `ErrNoBackend` - No keyring backend available
  - `ErrDaemonNotRunning` - Keyring daemon not running
- **Functions**:
  - `CheckDependencies() error` - Returns error with install instructions if deps missing
  - `NeedsInstallPrompt() bool` - Returns true if user needs to install deps
  - `CanUseKeyring() bool` - Convenience function for dependency checking
  - `GetSetupInstructions() string` - Human-readable setup instructions
  - `ValidateSetup() (bool, string)` - Detailed status for diagnostics

### 3. `pkg/keyring/keyring_test.go` (305 lines)
Comprehensive test suite with:
- Tests for all public functions
- Platform-specific test handling (Linux vs non-Linux)
- Timeout protection for tests that may require user interaction
- 14 test cases total
- All tests pass (with appropriate skips on Linux in short mode)
- 44.1% code coverage

## Key Implementation Details

### Service Configuration
- **Service Name**: `"mpv-manager"`
- **Password Key**: `"sudo-password"`

### Backend Priority (Linux)
1. SecretService (GNOME Keyring/libsecret)
2. KWallet (KDE Wallet)
3. Pass (password-store)
4. File (encrypted file-based fallback)

### Distro Detection
Reads `/etc/os-release` and maps to families:
- **debian**: Ubuntu, Debian, Linux Mint, Pop!_OS, elementary OS
- **fedora**: Fedora, RHEL, CentOS, Rocky Linux, AlmaLinux
- **arch**: Arch, Manjaro, EndeavourOS, Garuda
- **suse**: openSUSE Tumbleweed/Leap
- **unknown**: Falls back to generic instructions

### Desktop Environment Detection
Checks `XDG_CURRENT_DESKTOP` and `DESKTOP_SESSION` env vars, normalizes to: GNOME, KDE, XFCE, LXDE, MATE, Cinnamon, Budgie, Deepin, Pantheon, i3/Sway, Awesome, bspwm, dwm

### Install Hints by Distro
- **debian**: `sudo apt install gnome-keyring libsecret-1-dev`
- **fedora**: `sudo dnf install gnome-keyring libsecret-devel`
- **arch**: `sudo pacman -S gnome-keyring libsecret`
- **suse**: `sudo zypper install gnome-keyring libsecret-devel`
- **unknown**: Generic message based on DE

### Non-Linux Platforms
- **Windows**: Uses native Credential Manager
- **macOS**: Uses native Keychain
- Both platforms return immediately with appropriate behavior (no prompts, always available)

### File Backend Configuration
For non-interactive use with file backend:
- Uses fixed password: `"mpv-manager-file-keyring"`
- Less secure but allows non-interactive operation
- Suitable for headless environments

## Test Results
```
=== RUN   TestDetectStatus          --- PASS
=== RUN   TestCheckDependencies     --- PASS
=== RUN   TestNeedsInstallPrompt    --- PASS
=== RUN   TestCanUseKeyring         --- PASS
=== RUN   TestOpen                  --- SKIP (Linux short mode)
=== RUN   TestStoreAndGetPassword   --- SKIP (Linux)
=== RUN   TestStoreEmptyPassword    --- PASS
=== RUN   TestGetSetupInstructions  --- PASS
=== RUN   TestValidateSetup         --- SKIP (Linux short mode)
=== RUN   TestNormalizeDesktopEnv   --- PASS
=== RUN   TestDetectDistro          --- PASS
=== RUN   TestDetectDesktopEnvironment --- PASS
=== RUN   TestGenerateInstallHint   --- PASS
=== RUN   TestBackendTypeConstants  --- PASS
=== RUN   TestStatusJSONTags        --- PASS
PASS
coverage: 44.1% of statements
```

## Usage Example

```go
import "gitgud.io/mike/mpv-manager/pkg/keyring"

// Check if keyring can be used
if keyring.NeedsInstallPrompt() {
    instructions := keyring.GetSetupInstructions()
    // Show instructions to user
    return
}

// Open keyring
kr, err := keyring.Open()
if err != nil {
    // Handle error
}

// Store password
err = kr.StorePassword("my-sudo-password")
if err != nil {
    // Handle error
}

// Retrieve password
password, err := kr.GetPassword()
if err != nil {
    // Handle error (no password stored)
}

// Use password for sudo
// ...

// Delete password when no longer needed
err = kr.DeletePassword()
```

## Next Steps

To integrate with Web UI:

1. **Add API endpoint** in `pkg/web/api.go`:
   - `GET /api/keyring/status` - Get keyring status
   - `POST /api/keyring/password` - Store password
   - `DELETE /api/keyring/password` - Delete password

2. **Create Web UI page** for password management:
   - Show keyring status and backend info
   - Form to enter/store password
   - Display install instructions if needed

3. **Modify installer** to use stored password:
   - Check for stored password before sudo operations
   - Use password with `sudo -S` for authentication
   - Handle password errors gracefully

4. **Add Web UI template** in `internal/webassets/templates/keyring.html`

## Dependencies Added
- `github.com/99designs/keyring@latest` - Multi-backend keyring library
