internal/update.go

941 lines · 31667 bytes

48 symbols in this file
  1package internal
  2
  3import (
  4	"encoding/json"
  5	"errors"
  6	"fmt"
  7	"io"
  8	"net/http"
  9	"os"
 10	"os/exec"
 11	"path/filepath"
 12	"regexp"
 13	"runtime"
 14	"strings"
 15	"sync"
 16	"time"
 17
 18	"github.com/charmbracelet/lipgloss"
 19	"golang.org/x/term"
 20)
 21
 22const (
 23	defaultUpdateRepo          = "Wraient/curd"
 24	updatePendingFileName      = "update_pending.json"
 25	backgroundUpdateIdleDelay  = 4 * time.Second
 26	defaultRemindLaterDuration = 24 * time.Hour
 27	maxReleaseNotesRunes       = 1200
 28)
 29
 30// updatePendingState is persisted under StoragePath so startup never blocks on
 31// network — a previous idle check stores availability for the next launch.
 32type updatePendingState struct {
 33	Available      bool   `json:"available"`
 34	LatestVersion  string `json:"latest_version"`
 35	LatestTag      string `json:"latest_tag"`
 36	ReleaseName    string `json:"release_name"`
 37	ReleaseNotes   string `json:"release_notes"`
 38	HTMLURL        string `json:"html_url"`
 39	AssetName      string `json:"asset_name"`
 40	CheckedAt      string `json:"checked_at"`
 41	SkippedVersion string `json:"skipped_version,omitempty"`
 42	RemindAfter    string `json:"remind_after,omitempty"`
 43}
 44
 45type githubReleaseAPI struct {
 46	TagName string `json:"tag_name"`
 47	Name    string `json:"name"`
 48	Body    string `json:"body"`
 49	HTMLURL string `json:"html_url"`
 50	Assets  []struct {
 51		Name               string `json:"name"`
 52		BrowserDownloadURL string `json:"browser_download_url"`
 53	} `json:"assets"`
 54}
 55
 56var backgroundUpdateOnce sync.Once
 57
 58func updatePendingPath(storagePath string) string {
 59	if strings.TrimSpace(storagePath) == "" {
 60		storagePath = GetStoragePath()
 61	}
 62	return filepath.Join(os.ExpandEnv(storagePath), updatePendingFileName)
 63}
 64
 65func loadUpdatePendingState(storagePath string) updatePendingState {
 66	path := updatePendingPath(storagePath)
 67	data, err := os.ReadFile(path)
 68	if err != nil {
 69		return updatePendingState{}
 70	}
 71	var state updatePendingState
 72	if err := json.Unmarshal(data, &state); err != nil {
 73		Log(fmt.Sprintf("Ignoring corrupt update state: %v", err))
 74		return updatePendingState{}
 75	}
 76	return state
 77}
 78
 79func saveUpdatePendingState(storagePath string, state updatePendingState) error {
 80	path := updatePendingPath(storagePath)
 81	if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
 82		return err
 83	}
 84	data, err := json.MarshalIndent(state, "", "  ")
 85	if err != nil {
 86		return err
 87	}
 88	return os.WriteFile(path, data, 0600)
 89}
 90
 91func curdReleaseBinaryName() (string, error) {
 92	switch runtime.GOOS {
 93	case "windows":
 94		if runtime.GOARCH == "arm64" {
 95			return "curd-windows-arm64.exe", nil
 96		}
 97		return "curd-windows-x86_64.exe", nil
 98	case "darwin":
 99		switch runtime.GOARCH {
100		case "amd64":
101			return "curd-macos-x86_64", nil
102		case "arm64":
103			return "curd-macos-arm64", nil
104		default:
105			return "curd-macos-universal", nil
106		}
107	case "linux":
108		switch runtime.GOARCH {
109		case "amd64":
110			return "curd-linux-x86_64", nil
111		case "arm64":
112			return "curd-linux-arm64", nil
113		default:
114			return "", fmt.Errorf("unsupported Linux architecture: %s", runtime.GOARCH)
115		}
116	default:
117		return "", fmt.Errorf("unsupported operating system: %s", runtime.GOOS)
118	}
119}
120
121func normalizeReleaseVersion(tag string) string {
122	tag = strings.TrimSpace(tag)
123	tag = strings.TrimPrefix(tag, "v")
124	tag = strings.TrimPrefix(tag, "V")
125	return tag
126}
127
128func truncateReleaseNotes(notes string) string {
129	notes = strings.TrimSpace(notes)
130	if notes == "" {
131		return "(No release notes provided.)"
132	}
133	runes := []rune(notes)
134	if len(runes) <= maxReleaseNotesRunes {
135		return notes
136	}
137	return string(runes[:maxReleaseNotesRunes]) + "\n… (truncated)"
138}
139
140func fetchLatestGitHubRelease(repo string) (githubReleaseAPI, error) {
141	if strings.TrimSpace(repo) == "" {
142		repo = defaultUpdateRepo
143	}
144	url := fmt.Sprintf("https://api.github.com/repos/%s/releases/latest", repo)
145	req, err := http.NewRequest(http.MethodGet, url, nil)
146	if err != nil {
147		return githubReleaseAPI{}, err
148	}
149	req.Header.Set("Accept", "application/vnd.github+json")
150	req.Header.Set("User-Agent", "curd-update-check")
151
152	client := sharedHTTPClient
153	if client == nil {
154		client = &http.Client{Timeout: 15 * time.Second}
155	}
156	resp, err := client.Do(req)
157	if err != nil {
158		return githubReleaseAPI{}, err
159	}
160	defer resp.Body.Close()
161	if resp.StatusCode != http.StatusOK {
162		body, _ := io.ReadAll(io.LimitReader(resp.Body, 512))
163		return githubReleaseAPI{}, fmt.Errorf("github releases API status %d: %s", resp.StatusCode, strings.TrimSpace(string(body)))
164	}
165	var release githubReleaseAPI
166	if err := json.NewDecoder(resp.Body).Decode(&release); err != nil {
167		return githubReleaseAPI{}, err
168	}
169	if strings.TrimSpace(release.TagName) == "" {
170		return githubReleaseAPI{}, fmt.Errorf("latest release has no tag")
171	}
172	return release, nil
173}
174
175func isUpdateNewer(latest, current string) bool {
176	latest = normalizeReleaseVersion(latest)
177	current = normalizeReleaseVersion(current)
178	if latest == "" || current == "" {
179		return false
180	}
181	return versionLess(current, latest)
182}
183
184// StartBackgroundUpdateCheck runs after a short idle delay so startup is not blocked.
185// Results are written to StoragePath/update_pending.json for the next launch.
186func StartBackgroundUpdateCheck(config *CurdConfig, currentVersion string) {
187	if config == nil || !config.CheckUpdates {
188		return
189	}
190	backgroundUpdateOnce.Do(func() {
191		go func() {
192			time.Sleep(backgroundUpdateIdleDelay)
193			if err := checkForUpdateInBackground(config, currentVersion); err != nil {
194				Log(fmt.Sprintf("Background update check failed: %v", err))
195			}
196		}()
197	})
198}
199
200func checkForUpdateInBackground(config *CurdConfig, currentVersion string) error {
201	storagePath := config.StoragePath
202	state := loadUpdatePendingState(storagePath)
203
204	// Honor "remind later" without hitting the network repeatedly if still waiting.
205	if state.RemindAfter != "" {
206		if until, err := time.Parse(time.RFC3339, state.RemindAfter); err == nil && time.Now().Before(until) {
207			Log(fmt.Sprintf("Skipping update check until %s", state.RemindAfter))
208			return nil
209		}
210	}
211
212	release, err := fetchLatestGitHubRelease(defaultUpdateRepo)
213	if err != nil {
214		return err
215	}
216	latest := normalizeReleaseVersion(release.TagName)
217	state.CheckedAt = time.Now().UTC().Format(time.RFC3339)
218	state.LatestTag = release.TagName
219	state.LatestVersion = latest
220	state.ReleaseName = strings.TrimSpace(release.Name)
221	if state.ReleaseName == "" {
222		state.ReleaseName = "Curd " + latest
223	}
224	state.ReleaseNotes = truncateReleaseNotes(release.Body)
225	state.HTMLURL = release.HTMLURL
226
227	if asset, assetErr := curdReleaseBinaryName(); assetErr == nil {
228		state.AssetName = asset
229	}
230
231	if state.SkippedVersion != "" && normalizeReleaseVersion(state.SkippedVersion) == latest {
232		state.Available = false
233		return saveUpdatePendingState(storagePath, state)
234	}
235
236	if !isUpdateNewer(latest, currentVersion) {
237		state.Available = false
238		return saveUpdatePendingState(storagePath, state)
239	}
240
241	state.Available = true
242	// Clear remind-later once a check found something actionable after the window.
243	if state.RemindAfter != "" {
244		if until, err := time.Parse(time.RFC3339, state.RemindAfter); err == nil && !time.Now().Before(until) {
245			state.RemindAfter = ""
246		}
247	}
248	Log(fmt.Sprintf("Update available: %s → %s", currentVersion, latest))
249	return saveUpdatePendingState(storagePath, state)
250}
251
252func pendingUpdateShouldPrompt(config *CurdConfig, currentVersion string, state updatePendingState) bool {
253	if config == nil || !config.CheckUpdates {
254		return false
255	}
256	if !state.Available || strings.TrimSpace(state.LatestVersion) == "" {
257		return false
258	}
259	if !isUpdateNewer(state.LatestVersion, currentVersion) {
260		return false
261	}
262	if normalizeReleaseVersion(state.SkippedVersion) == normalizeReleaseVersion(state.LatestVersion) {
263		return false
264	}
265	if state.RemindAfter != "" {
266		if until, err := time.Parse(time.RFC3339, state.RemindAfter); err == nil && time.Now().Before(until) {
267			return false
268		}
269	}
270	return true
271}
272
273func formatLocalTime(t time.Time) string {
274	return t.In(time.Local).Format("Mon Jan 2 2006, 3:04 PM MST")
275}
276
277func escapePango(s string) string {
278	s = strings.ReplaceAll(s, "&", "&amp;")
279	s = strings.ReplaceAll(s, "<", "&lt;")
280	s = strings.ReplaceAll(s, ">", "&gt;")
281	return s
282}
283
284var (
285	mdBoldRe  = regexp.MustCompile(`\*\*(.+?)\*\*`)
286	mdCodeRe  = regexp.MustCompile("`([^`]+)`")
287	mdLinkRe  = regexp.MustCompile(`\[([^\]]+)\]\(([^)]+)\)`)
288	mdURLRe   = regexp.MustCompile(`https?://[^\s<>\]]+`)
289	ansiStrip = regexp.MustCompile(`\x1b\[[0-9;]*m`)
290	pangoStrip = regexp.MustCompile(`<[^>]*>`)
291)
292
293// markdownToPango turns common GitHub release markdown into Rofi-friendly Pango.
294func markdownToPango(md string) string {
295	lines := strings.Split(strings.ReplaceAll(md, "\r\n", "\n"), "\n")
296	out := make([]string, 0, len(lines))
297	for _, line := range lines {
298		trimmed := strings.TrimSpace(line)
299		switch {
300		case trimmed == "":
301			out = append(out, "")
302			continue
303		case strings.HasPrefix(trimmed, "### "):
304			text := escapePango(strings.TrimPrefix(trimmed, "### "))
305			out = append(out, `<span foreground="#FFD166"><b>`+text+`</b></span>`)
306		case strings.HasPrefix(trimmed, "## "):
307			text := escapePango(strings.TrimPrefix(trimmed, "## "))
308			out = append(out, `<span foreground="#7CB9E8" size="large"><b>`+text+`</b></span>`)
309		case strings.HasPrefix(trimmed, "# "):
310			text := escapePango(strings.TrimPrefix(trimmed, "# "))
311			out = append(out, `<span foreground="#7CFC98" size="large"><b>`+text+`</b></span>`)
312		case strings.HasPrefix(trimmed, "- ") || strings.HasPrefix(trimmed, "* "):
313			body := strings.TrimPrefix(strings.TrimPrefix(trimmed, "- "), "* ")
314			out = append(out, `<span foreground="#98FB98">•</span> `+inlineMarkdownToPango(body))
315		case strings.HasPrefix(trimmed, "**Full Changelog**") || strings.HasPrefix(strings.ToLower(trimmed), "**full changelog**"):
316			out = append(out, `<span foreground="#B0B0B0">`+inlineMarkdownToPango(trimmed)+`</span>`)
317		default:
318			out = append(out, inlineMarkdownToPango(trimmed))
319		}
320	}
321	return strings.Join(out, "\n")
322}
323
324func inlineMarkdownToPango(s string) string {
325	// Links first (before escaping full string piece by piece)
326	s = mdLinkRe.ReplaceAllStringFunc(s, func(m string) string {
327		parts := mdLinkRe.FindStringSubmatch(m)
328		if len(parts) != 3 {
329			return escapePango(m)
330		}
331		return `<span foreground="#6EC6FF" underline="single">` + escapePango(parts[1]) + `</span>`
332	})
333	// Escape remaining raw text while preserving spans we inserted — do a simple pass:
334	// split on existing span tags is hard; re-process from original for bold/code on non-link text.
335	// Safer path: escape whole line then re-apply patterns on escaped text where ** still present.
336	if !strings.Contains(s, "<span") {
337		s = escapePango(s)
338		s = mdBoldRe.ReplaceAllString(s, `<span foreground="#FFFFFF"><b>$1</b></span>`)
339		s = mdCodeRe.ReplaceAllString(s, `<span foreground="#E0B0FF" face="monospace">$1</span>`)
340		s = mdURLRe.ReplaceAllStringFunc(s, func(u string) string {
341			return `<span foreground="#6EC6FF" underline="single">` + u + `</span>`
342		})
343		return s
344	}
345	// Already has link spans — only lightly touch remaining ** if any outside tags
346	s = mdBoldRe.ReplaceAllString(s, `<b>$1</b>`)
347	return s
348}
349
350// markdownToTerminal colors release notes for CLI (lipgloss), easy on the eyes.
351func markdownToTerminal(md string) string {
352	heading := lipgloss.NewStyle().Foreground(lipgloss.Color("#7CB9E8")).Bold(true)
353	subhead := lipgloss.NewStyle().Foreground(lipgloss.Color("#FFD166")).Bold(true)
354	bullet := lipgloss.NewStyle().Foreground(lipgloss.Color("#98FB98"))
355	body := lipgloss.NewStyle().Foreground(lipgloss.Color("#E6E6FA"))
356	muted := lipgloss.NewStyle().Foreground(lipgloss.Color("#9A9A9A"))
357	link := lipgloss.NewStyle().Foreground(lipgloss.Color("#6EC6FF")).Underline(true)
358
359	lines := strings.Split(strings.ReplaceAll(md, "\r\n", "\n"), "\n")
360	out := make([]string, 0, len(lines))
361	for _, line := range lines {
362		trimmed := strings.TrimSpace(line)
363		switch {
364		case trimmed == "":
365			out = append(out, "")
366		case strings.HasPrefix(trimmed, "### "):
367			out = append(out, subhead.Render(strings.TrimPrefix(trimmed, "### ")))
368		case strings.HasPrefix(trimmed, "## "):
369			out = append(out, heading.Render(strings.TrimPrefix(trimmed, "## ")))
370		case strings.HasPrefix(trimmed, "# "):
371			out = append(out, heading.Render(strings.TrimPrefix(trimmed, "# ")))
372		case strings.HasPrefix(trimmed, "- ") || strings.HasPrefix(trimmed, "* "):
373			item := strings.TrimPrefix(strings.TrimPrefix(trimmed, "- "), "* ")
374			item = mdBoldRe.ReplaceAllString(item, "$1")
375			item = mdLinkRe.ReplaceAllString(item, "$1")
376			out = append(out, bullet.Render("• ")+body.Render(item))
377		case strings.HasPrefix(trimmed, "http://") || strings.HasPrefix(trimmed, "https://"):
378			out = append(out, link.Render(trimmed))
379		case strings.Contains(strings.ToLower(trimmed), "full changelog"):
380			out = append(out, muted.Render(mdLinkRe.ReplaceAllString(trimmed, "$1 ($2)")))
381		default:
382			t := mdBoldRe.ReplaceAllString(trimmed, "$1")
383			t = mdLinkRe.ReplaceAllString(t, "$1")
384			out = append(out, body.Render(t))
385		}
386	}
387	return strings.Join(out, "\n")
388}
389
390func buildUpdatePromptMessage(currentVersion string, state updatePendingState) (prompt, message string) {
391	return buildUpdatePromptMessageMode(currentVersion, state, false)
392}
393
394// buildUpdatePromptMessageMode formats the update banner.
395// forRofi=true emits Pango markup for Rofi -mesg; false emits lipgloss ANSI for the terminal.
396func buildUpdatePromptMessageMode(currentVersion string, state updatePendingState, forRofi bool) (prompt, message string) {
397	from := normalizeReleaseVersion(currentVersion)
398	to := normalizeReleaseVersion(state.LatestVersion)
399	prompt = fmt.Sprintf("✨ Update %s → %s", from, to)
400
401	notes := strings.TrimSpace(state.ReleaseNotes)
402	if notes == "" {
403		notes = "(No release notes on GitHub for this release.)"
404	}
405
406	if forRofi {
407		var b strings.Builder
408		title := state.ReleaseName
409		if title == "" {
410			title = "Curd " + to
411		}
412		b.WriteString(`<span foreground="#7CFC98" size="large"><b>🚀 ` + escapePango(title) + `</b></span>` + "\n")
413		b.WriteString(`<span foreground="#E6E6FA">Current </span>`)
414		b.WriteString(`<span foreground="#FF8A80"><b>` + escapePango(from) + `</b></span>`)
415		b.WriteString(`<span foreground="#E6E6FA">  →  Latest </span>`)
416		b.WriteString(`<span foreground="#7CFC98"><b>` + escapePango(to) + `</b></span>` + "\n")
417		if state.HTMLURL != "" {
418			b.WriteString(`<span foreground="#6EC6FF" underline="single">` + escapePango(state.HTMLURL) + `</span>` + "\n")
419		}
420		b.WriteString("\n")
421		b.WriteString(markdownToPango(notes))
422		message = strings.TrimSpace(b.String())
423		// Pango is verbose; soft-cap markup length.
424		if len([]rune(message)) > maxReleaseNotesRunes*3 {
425			r := []rune(message)
426			message = string(r[:maxReleaseNotesRunes*3]) + "\n<span foreground=\"#9A9A9A\">… (truncated — full notes on GitHub)</span>"
427		}
428		return prompt, message
429	}
430
431	// CLI / terminal
432	title := lipgloss.NewStyle().Foreground(lipgloss.Color("#7CFC98")).Bold(true)
433	label := lipgloss.NewStyle().Foreground(lipgloss.Color("#E6E6FA"))
434	oldV := lipgloss.NewStyle().Foreground(lipgloss.Color("#FF8A80")).Bold(true)
435	newV := lipgloss.NewStyle().Foreground(lipgloss.Color("#7CFC98")).Bold(true)
436	link := lipgloss.NewStyle().Foreground(lipgloss.Color("#6EC6FF")).Underline(true)
437
438	var b strings.Builder
439	name := state.ReleaseName
440	if name == "" {
441		name = "Curd " + to
442	}
443	b.WriteString(title.Render("🚀 "+name) + "\n")
444	b.WriteString(label.Render("Current ") + oldV.Render(from) + label.Render("  →  Latest ") + newV.Render(to) + "\n")
445	if state.HTMLURL != "" {
446		b.WriteString(link.Render(state.HTMLURL) + "\n")
447	}
448	b.WriteString("\n")
449	b.WriteString(markdownToTerminal(notes))
450	message = strings.TrimSpace(b.String())
451	// Cap plain-ish length for terminal
452	plain := ansiStrip.ReplaceAllString(message, "")
453	if len([]rune(plain)) > maxReleaseNotesRunes {
454		// Keep header + truncated notes roughly
455		message = message + "\n" + label.Render("… (truncated — full notes on GitHub)")
456	}
457	return prompt, message
458}
459
460func updateActionOptions() []SelectionOption {
461	// Emoji prefixes: lively, ordered, no numeric indices; preserveOrder keeps this order.
462	return []SelectionOption{
463		{Key: "update", Label: "🚀  Update now"},
464		{Key: "later", Label: "⏰  Remind me later"},
465		{Key: "skip", Label: "⏭️  Skip this version"},
466		{Key: "disable", Label: "🔕  Turn off automatic update checks"},
467		{Key: "continue", Label: "▶️  Continue without updating"},
468	}
469}
470
471// refreshUpdateStateFromGitHub reloads tag/name/body/url from the live release API
472// so the prompt shows real markdown notes instead of a stale/test seed.
473func refreshUpdateStateFromGitHub(state *updatePendingState) {
474	if state == nil {
475		return
476	}
477	release, err := fetchLatestGitHubRelease(defaultUpdateRepo)
478	if err != nil {
479		Log(fmt.Sprintf("Could not refresh release notes from GitHub: %v", err))
480		return
481	}
482	latest := normalizeReleaseVersion(release.TagName)
483	if latest == "" {
484		return
485	}
486	// If GitHub moved past what we flagged, still show the newest release.
487	state.LatestTag = release.TagName
488	state.LatestVersion = latest
489	state.ReleaseName = strings.TrimSpace(release.Name)
490	if state.ReleaseName == "" {
491		state.ReleaseName = "Curd " + latest
492	}
493	// Full markdown body from the GitHub release page (API `body` field).
494	// Do not seed/test stubs here — always prefer live API content when online.
495	state.ReleaseNotes = strings.TrimSpace(release.Body)
496	state.HTMLURL = release.HTMLURL
497	state.CheckedAt = time.Now().UTC().Format(time.RFC3339)
498	if asset, assetErr := curdReleaseBinaryName(); assetErr == nil {
499		state.AssetName = asset
500	}
501	state.Available = true
502}
503
504// updateUserMessage prints a single status line. With Rofi mode, CurdOut becomes
505// notify-send — so we only send one short notification (or log) for status.
506func updateUserMessage(config *CurdConfig, msg string) {
507	msg = strings.TrimSpace(msg)
508	if msg == "" {
509		return
510	}
511	Log(msg)
512	if config != nil && config.RofiSelection {
513		// One short desktop notification, not a barrage of CurdOut lines.
514		_ = exec.Command("notify-send", "-a", "Curd",
515			"-h", "string:x-canonical-private-synchronous:curd-update",
516			"Curd", msg).Run()
517		return
518	}
519	fmt.Println(msg)
520}
521
522// HandlePendingUpdatePrompt shows a previously detected update (from idle check).
523// Returns true if the caller should exit (user updated or chose to quit the session).
524func HandlePendingUpdatePrompt(config *CurdConfig, currentVersion string) bool {
525	if config == nil || !config.CheckUpdates {
526		return false
527	}
528	state := loadUpdatePendingState(config.StoragePath)
529	if !pendingUpdateShouldPrompt(config, currentVersion, state) {
530		return false
531	}
532
533	// Pull live release markdown from GitHub so notes match the release page.
534	refreshUpdateStateFromGitHub(&state)
535	if !pendingUpdateShouldPrompt(config, currentVersion, state) {
536		// e.g. already up to date after refresh
537		state.Available = false
538		_ = saveUpdatePendingState(config.StoragePath, state)
539		return false
540	}
541	_ = saveUpdatePendingState(config.StoragePath, state)
542
543	// Fixed order (Update now first). Emoji labels; preserveOrder for CLI.
544	options := updateActionOptions()
545	prompt, message := buildUpdatePromptMessageMode(currentVersion, state, config.RofiSelection)
546
547	var selected SelectionOption
548	var err error
549	if config.RofiSelection {
550		// Pango-colored notes in -mesg; one Rofi UI, no notify spam.
551		selected, err = RofiSelectWithMessage(options, false, prompt, message)
552	} else {
553		header := lipgloss.NewStyle().Foreground(lipgloss.Color("#FFD166")).Bold(true)
554		fmt.Println(header.Render(prompt))
555		fmt.Println(message)
556		fmt.Println()
557		selected, err = promptSelectOrdered(options)
558	}
559	if err != nil {
560		return false
561	}
562	selected = NormalizeSelectionKey(selected)
563	// Quit from the pinned menu must exit the whole program (not fall through to curd).
564	if SelectionMeansQuit(selected) {
565		ExitCurd(nil)
566		return true
567	}
568	// Back / empty = dismiss update prompt and continue the session.
569	if SelectionMeansBack(selected) || selected.Key == "continue" || selected.Key == "" {
570		return false
571	}
572
573	switch selected.Key {
574	case "update":
575		updateUserMessage(config, "Downloading and installing update…")
576		if err := UpdateCurd(defaultUpdateRepo, "curd"); err != nil {
577			updateUserMessage(config, fmt.Sprintf("Update failed: %v", err))
578			Log(fmt.Sprintf("Update failed: %v", err))
579			return false
580		}
581		state.Available = false
582		state.RemindAfter = ""
583		_ = saveUpdatePendingState(config.StoragePath, state)
584		updateUserMessage(config, fmt.Sprintf("Updated to %s. Please restart curd.", state.LatestVersion))
585		return true
586	case "later":
587		until := time.Now().Add(defaultRemindLaterDuration)
588		state.RemindAfter = until.UTC().Format(time.RFC3339)
589		state.Available = true
590		_ = saveUpdatePendingState(config.StoragePath, state)
591		updateUserMessage(config, fmt.Sprintf("Will remind again after %s.", formatLocalTime(until)))
592		return false
593	case "skip":
594		state.SkippedVersion = state.LatestVersion
595		state.Available = false
596		state.RemindAfter = ""
597		_ = saveUpdatePendingState(config.StoragePath, state)
598		updateUserMessage(config, fmt.Sprintf("Skipping version %s.", state.LatestVersion))
599		return false
600	case "disable":
601		if err := setConfigBoolOption(GlobalConfigPath, "CheckUpdates", false); err != nil {
602			updateUserMessage(config, fmt.Sprintf("Could not write config: %v", err))
603			Log(fmt.Sprintf("disable CheckUpdates: %v", err))
604		} else {
605			config.CheckUpdates = false
606			updateUserMessage(config, "Automatic update checks disabled (CheckUpdates=false).")
607		}
608		state.Available = false
609		_ = saveUpdatePendingState(config.StoragePath, state)
610		return false
611	default:
612		return false
613	}
614}
615
616func setConfigBoolOption(configPath, key string, value bool) error {
617	if strings.TrimSpace(configPath) == "" {
618		return fmt.Errorf("config path is empty")
619	}
620	configMap, err := LoadConfigFromFile(configPath)
621	if err != nil {
622		return err
623	}
624	_, existed := configMap[key]
625	if value {
626		configMap[key] = "true"
627	} else {
628		configMap[key] = "false"
629	}
630	if !existed {
631		return appendConfigKeys(configPath, configMap, []string{key})
632	}
633	return SaveConfigToFile(configPath, configMap)
634}
635
636func isPermissionError(err error) bool {
637	if err == nil {
638		return false
639	}
640	if errors.Is(err, os.ErrPermission) {
641		return true
642	}
643	msg := strings.ToLower(err.Error())
644	return strings.Contains(msg, "permission denied") ||
645		strings.Contains(msg, "access is denied") ||
646		strings.Contains(msg, "operation not permitted")
647}
648
649// isCrossDeviceError reports rename/link failures when src and dest are on
650// different filesystems (e.g. /tmp tmpfs → ~/.local/bin on disk).
651func isCrossDeviceError(err error) bool {
652	if err == nil {
653		return false
654	}
655	var linkErr *os.LinkError
656	if errors.As(err, &linkErr) {
657		err = linkErr.Err
658	}
659	msg := strings.ToLower(err.Error())
660	return strings.Contains(msg, "cross-device") ||
661		strings.Contains(msg, "cross device") ||
662		strings.Contains(msg, "exdev") ||
663		strings.Contains(msg, "invalid cross-device link")
664}
665
666func hasDisplay() bool {
667	return os.Getenv("DISPLAY") != "" || os.Getenv("WAYLAND_DISPLAY") != ""
668}
669
670func stdinIsTerminal() bool {
671	return term.IsTerminal(int(os.Stdin.Fd()))
672}
673
674// preferGUIPasswordPrompt decides whether to open a desktop password dialog.
675//
676//   - Rofi/desktop mode → GUI first (zenity/yad/kdialog)
677//   - Plain CLI with a TTY (e.g. `curd -u` in a terminal) → terminal only
678//   - No TTY but a display → GUI
679func preferGUIPasswordPrompt() bool {
680	rofi := false
681	if cfg := GetGlobalConfig(); cfg != nil {
682		rofi = cfg.RofiSelection
683	}
684	tty := stdinIsTerminal()
685
686	// Interactive CLI: never pop a GUI dialog just because DISPLAY is set.
687	if tty && !rofi {
688		return false
689	}
690	if rofi {
691		return true
692	}
693	// Headless of TTY (desktop launcher without a terminal): GUI if available.
694	return !tty && hasDisplay()
695}
696
697// promptSudoPasswordGUI tries GTK/desktop password dialogs (zenity → yad → kdialog).
698func promptSudoPasswordGUI(prompt string) (string, error) {
699	if prompt == "" {
700		prompt = "Enter your password to install the Curd update:"
701	}
702
703	type dialog struct {
704		name string
705		args []string
706	}
707	dialogs := []dialog{
708		// GTK (GNOME / many desktops)
709		{"zenity", []string{"--password", "--title=Curd Update", "--text=" + prompt}},
710		// GTK-based yad
711		{"yad", []string{"--entry", "--hide-text", "--title=Curd Update", "--text=" + prompt, "--button=OK:0", "--button=Cancel:1"}},
712		// KDE
713		{"kdialog", []string{"--title", "Curd Update", "--password", prompt}},
714	}
715
716	for _, d := range dialogs {
717		bin, err := exec.LookPath(d.name)
718		if err != nil {
719			continue
720		}
721		cmd := exec.Command(bin, d.args...)
722		out, err := cmd.Output()
723		if err != nil {
724			// User cancel or dialog error — try next tool only on "not found"; cancel stops.
725			var exitErr *exec.ExitError
726			if errors.As(err, &exitErr) {
727				// zenity/yad/kdialog: non-zero usually means cancel.
728				return "", fmt.Errorf("password dialog cancelled")
729			}
730			Log(fmt.Sprintf("password dialog %s failed: %v", d.name, err))
731			continue
732		}
733		password := strings.TrimRight(string(out), "\r\n")
734		if password == "" {
735			return "", fmt.Errorf("empty password")
736		}
737		Log(fmt.Sprintf("Collected sudo password via %s dialog", d.name))
738		return password, nil
739	}
740	return "", fmt.Errorf("no GUI password dialog available (tried zenity, yad, kdialog)")
741}
742
743func promptSudoPassword(prompt string) (string, error) {
744	if prompt == "" {
745		prompt = "Administrator password (sudo) to install update: "
746	}
747
748	rofi := false
749	if cfg := GetGlobalConfig(); cfg != nil {
750		rofi = cfg.RofiSelection
751	}
752	tty := stdinIsTerminal()
753
754	// Rofi/desktop: try zenity/yad/kdialog first.
755	if preferGUIPasswordPrompt() {
756		if password, err := promptSudoPasswordGUI(prompt); err == nil {
757			return password, nil
758		} else {
759			Log(fmt.Sprintf("GUI password prompt unavailable (%v)", err))
760			// Explicit cancel in GUI: only abort if we shouldn't fall back to TTY.
761			// In rofi mode with no TTY, cancel means cancel.
762			if strings.Contains(err.Error(), "cancelled") && (!tty || rofi) {
763				// If we still have a real terminal under us (rare with rofi), allow TTY
764				// fallback only when not in rofi mode.
765				if !tty {
766					return "", err
767				}
768				if rofi {
769					// Rofi session: user closed the dialog on purpose.
770					return "", err
771				}
772			}
773			// GUI missing/failed → fall through to terminal when possible.
774		}
775	}
776
777	// Terminal path (CLI `curd -u`, or GUI unavailable).
778	if !tty {
779		return "", fmt.Errorf("no terminal available for password entry; install zenity/yad/kdialog for a GUI prompt")
780	}
781	fmt.Fprint(os.Stderr, prompt)
782	if !strings.HasSuffix(prompt, " ") {
783		fmt.Fprint(os.Stderr, " ")
784	}
785	password, err := term.ReadPassword(int(os.Stdin.Fd()))
786	fmt.Fprintln(os.Stderr)
787	if err != nil {
788		return "", err
789	}
790	return string(password), nil
791}
792
793func installExecutableWithSudo(src, dest string) error {
794	// Prefer install(1) for mode bits; fall back to cp + chmod.
795	password, err := promptSudoPassword("Administrator password (sudo) to install update: ")
796	if err != nil {
797		return fmt.Errorf("read sudo password: %w", err)
798	}
799	if strings.TrimSpace(password) == "" {
800		return fmt.Errorf("empty sudo password")
801	}
802
803	try := func(name string, args ...string) error {
804		cmd := exec.Command(name, args...)
805		cmd.Stdin = strings.NewReader(password + "\n")
806		cmd.Stdout = os.Stdout
807		cmd.Stderr = os.Stderr
808		return cmd.Run()
809	}
810
811	// -S: read password from stdin; -p '': no extra prompt
812	if err := try("sudo", "-S", "-p", "", "install", "-m", "755", src, dest); err == nil {
813		return nil
814	} else {
815		Log(fmt.Sprintf("sudo install failed: %v", err))
816	}
817	if err := try("sudo", "-S", "-p", "", "cp", src, dest); err != nil {
818		return fmt.Errorf("sudo install failed: %w", err)
819	}
820	_ = try("sudo", "-S", "-p", "", "chmod", "755", dest)
821	return nil
822}
823
824// createUpdateTempFile prefers a sibling of the executable (same FS as install
825// path). Falls back to os.TempDir when the install directory is not writable.
826func createUpdateTempFile(executablePath, binaryName string) (string, *os.File, error) {
827	dir := filepath.Dir(executablePath)
828	// Try same directory first for atomic rename.
829	if f, err := os.CreateTemp(dir, ".curd-download-*"); err == nil {
830		return f.Name(), f, nil
831	}
832	// Fall back to system temp (may be cross-device; replaceExecutable handles that).
833	name := "curd-update-" + binaryName
834	if binaryName == "" {
835		name = "curd-update-bin"
836	}
837	path := filepath.Join(os.TempDir(), name)
838	f, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0755)
839	if err != nil {
840		return "", nil, err
841	}
842	return path, f, nil
843}
844
845func copyFileReplace(src, dst string) error {
846	in, err := os.Open(src)
847	if err != nil {
848		return err
849	}
850	defer in.Close()
851
852	// Write to a sibling temp on the destination filesystem, then rename into place.
853	dir := filepath.Dir(dst)
854	tmp, err := os.CreateTemp(dir, ".curd-update-*")
855	if err != nil {
856		return err
857	}
858	tmpName := tmp.Name()
859	cleanup := true
860	defer func() {
861		if cleanup {
862			_ = os.Remove(tmpName)
863		}
864	}()
865
866	if err := tmp.Chmod(0755); err != nil {
867		_ = tmp.Close()
868		return err
869	}
870	if _, err := io.Copy(tmp, in); err != nil {
871		_ = tmp.Close()
872		return err
873	}
874	if err := tmp.Sync(); err != nil {
875		_ = tmp.Close()
876		return err
877	}
878	if err := tmp.Close(); err != nil {
879		return err
880	}
881
882	// Atomic replace when possible (same directory = same filesystem).
883	if err := os.Rename(tmpName, dst); err != nil {
884		// Windows / busy binary: move dest aside first.
885		oldPath := dst + ".old"
886		_ = os.Remove(oldPath)
887		if renOld := os.Rename(dst, oldPath); renOld != nil && !os.IsNotExist(renOld) {
888			return renOld
889		}
890		if renNew := os.Rename(tmpName, dst); renNew != nil {
891			_ = os.Rename(oldPath, dst)
892			return renNew
893		}
894		_ = os.Remove(oldPath)
895	}
896	cleanup = false
897	return nil
898}
899
900// replaceExecutable installs the downloaded binary over the running executable.
901// Handles: same-FS rename, cross-device copy, busy binary swap, and sudo when needed.
902func replaceExecutable(tmpPath, executablePath string) error {
903	// 1) Fast path: rename when both paths share a filesystem.
904	if err := os.Rename(tmpPath, executablePath); err == nil {
905		return nil
906	} else if isPermissionError(err) {
907		updateUserMessage(GetGlobalConfig(), "Update needs elevated permissions to replace the installed binary.")
908		if sudoErr := installExecutableWithSudo(tmpPath, executablePath); sudoErr != nil {
909			return sudoErr
910		}
911		_ = os.Remove(tmpPath)
912		return nil
913	} else if !isCrossDeviceError(err) {
914		// Unexpected rename failure — still try copy-into-place before giving up.
915		Log(fmt.Sprintf("rename to %s failed (%v); trying copy replace", executablePath, err))
916	}
917
918	// 2) Cross-device (or other rename failure): copy onto dest filesystem then swap.
919	if err := copyFileReplace(tmpPath, executablePath); err == nil {
920		_ = os.Remove(tmpPath)
921		return nil
922	} else if isPermissionError(err) {
923		updateUserMessage(GetGlobalConfig(), "Update needs elevated permissions to replace the installed binary.")
924		if sudoErr := installExecutableWithSudo(tmpPath, executablePath); sudoErr != nil {
925			return fmt.Errorf("failed to replace executable: %w", sudoErr)
926		}
927		_ = os.Remove(tmpPath)
928		return nil
929	} else {
930		// Last resort: sudo install from original temp (covers weird FS layouts).
931		if isCrossDeviceError(err) || runtime.GOOS != "windows" {
932			Log(fmt.Sprintf("copy replace failed (%v); trying sudo", err))
933			updateUserMessage(GetGlobalConfig(), "Update needs elevated permissions to replace the installed binary.")
934			if sudoErr := installExecutableWithSudo(tmpPath, executablePath); sudoErr == nil {
935				_ = os.Remove(tmpPath)
936				return nil
937			}
938		}
939		return fmt.Errorf("failed to replace executable: %w", err)
940	}
941}