internal/update.go

940 lines · 31623 bytes

  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)
291
292// markdownToPango turns common GitHub release markdown into Rofi-friendly Pango.
293func markdownToPango(md string) string {
294	lines := strings.Split(strings.ReplaceAll(md, "\r\n", "\n"), "\n")
295	out := make([]string, 0, len(lines))
296	for _, line := range lines {
297		trimmed := strings.TrimSpace(line)
298		switch {
299		case trimmed == "":
300			out = append(out, "")
301			continue
302		case strings.HasPrefix(trimmed, "### "):
303			text := escapePango(strings.TrimPrefix(trimmed, "### "))
304			out = append(out, `<span foreground="#FFD166"><b>`+text+`</b></span>`)
305		case strings.HasPrefix(trimmed, "## "):
306			text := escapePango(strings.TrimPrefix(trimmed, "## "))
307			out = append(out, `<span foreground="#7CB9E8" size="large"><b>`+text+`</b></span>`)
308		case strings.HasPrefix(trimmed, "# "):
309			text := escapePango(strings.TrimPrefix(trimmed, "# "))
310			out = append(out, `<span foreground="#7CFC98" size="large"><b>`+text+`</b></span>`)
311		case strings.HasPrefix(trimmed, "- ") || strings.HasPrefix(trimmed, "* "):
312			body := strings.TrimPrefix(strings.TrimPrefix(trimmed, "- "), "* ")
313			out = append(out, `<span foreground="#98FB98">•</span> `+inlineMarkdownToPango(body))
314		case strings.HasPrefix(trimmed, "**Full Changelog**") || strings.HasPrefix(strings.ToLower(trimmed), "**full changelog**"):
315			out = append(out, `<span foreground="#B0B0B0">`+inlineMarkdownToPango(trimmed)+`</span>`)
316		default:
317			out = append(out, inlineMarkdownToPango(trimmed))
318		}
319	}
320	return strings.Join(out, "\n")
321}
322
323func inlineMarkdownToPango(s string) string {
324	// Links first (before escaping full string piece by piece)
325	s = mdLinkRe.ReplaceAllStringFunc(s, func(m string) string {
326		parts := mdLinkRe.FindStringSubmatch(m)
327		if len(parts) != 3 {
328			return escapePango(m)
329		}
330		return `<span foreground="#6EC6FF" underline="single">` + escapePango(parts[1]) + `</span>`
331	})
332	// Escape remaining raw text while preserving spans we inserted — do a simple pass:
333	// split on existing span tags is hard; re-process from original for bold/code on non-link text.
334	// Safer path: escape whole line then re-apply patterns on escaped text where ** still present.
335	if !strings.Contains(s, "<span") {
336		s = escapePango(s)
337		s = mdBoldRe.ReplaceAllString(s, `<span foreground="#FFFFFF"><b>$1</b></span>`)
338		s = mdCodeRe.ReplaceAllString(s, `<span foreground="#E0B0FF" face="monospace">$1</span>`)
339		s = mdURLRe.ReplaceAllStringFunc(s, func(u string) string {
340			return `<span foreground="#6EC6FF" underline="single">` + u + `</span>`
341		})
342		return s
343	}
344	// Already has link spans — only lightly touch remaining ** if any outside tags
345	s = mdBoldRe.ReplaceAllString(s, `<b>$1</b>`)
346	return s
347}
348
349// markdownToTerminal colors release notes for CLI (lipgloss), easy on the eyes.
350func markdownToTerminal(md string) string {
351	heading := lipgloss.NewStyle().Foreground(lipgloss.Color("#7CB9E8")).Bold(true)
352	subhead := lipgloss.NewStyle().Foreground(lipgloss.Color("#FFD166")).Bold(true)
353	bullet := lipgloss.NewStyle().Foreground(lipgloss.Color("#98FB98"))
354	body := lipgloss.NewStyle().Foreground(lipgloss.Color("#E6E6FA"))
355	muted := lipgloss.NewStyle().Foreground(lipgloss.Color("#9A9A9A"))
356	link := lipgloss.NewStyle().Foreground(lipgloss.Color("#6EC6FF")).Underline(true)
357
358	lines := strings.Split(strings.ReplaceAll(md, "\r\n", "\n"), "\n")
359	out := make([]string, 0, len(lines))
360	for _, line := range lines {
361		trimmed := strings.TrimSpace(line)
362		switch {
363		case trimmed == "":
364			out = append(out, "")
365		case strings.HasPrefix(trimmed, "### "):
366			out = append(out, subhead.Render(strings.TrimPrefix(trimmed, "### ")))
367		case strings.HasPrefix(trimmed, "## "):
368			out = append(out, heading.Render(strings.TrimPrefix(trimmed, "## ")))
369		case strings.HasPrefix(trimmed, "# "):
370			out = append(out, heading.Render(strings.TrimPrefix(trimmed, "# ")))
371		case strings.HasPrefix(trimmed, "- ") || strings.HasPrefix(trimmed, "* "):
372			item := strings.TrimPrefix(strings.TrimPrefix(trimmed, "- "), "* ")
373			item = mdBoldRe.ReplaceAllString(item, "$1")
374			item = mdLinkRe.ReplaceAllString(item, "$1")
375			out = append(out, bullet.Render("• ")+body.Render(item))
376		case strings.HasPrefix(trimmed, "http://") || strings.HasPrefix(trimmed, "https://"):
377			out = append(out, link.Render(trimmed))
378		case strings.Contains(strings.ToLower(trimmed), "full changelog"):
379			out = append(out, muted.Render(mdLinkRe.ReplaceAllString(trimmed, "$1 ($2)")))
380		default:
381			t := mdBoldRe.ReplaceAllString(trimmed, "$1")
382			t = mdLinkRe.ReplaceAllString(t, "$1")
383			out = append(out, body.Render(t))
384		}
385	}
386	return strings.Join(out, "\n")
387}
388
389func buildUpdatePromptMessage(currentVersion string, state updatePendingState) (prompt, message string) {
390	return buildUpdatePromptMessageMode(currentVersion, state, false)
391}
392
393// buildUpdatePromptMessageMode formats the update banner.
394// forRofi=true emits Pango markup for Rofi -mesg; false emits lipgloss ANSI for the terminal.
395func buildUpdatePromptMessageMode(currentVersion string, state updatePendingState, forRofi bool) (prompt, message string) {
396	from := normalizeReleaseVersion(currentVersion)
397	to := normalizeReleaseVersion(state.LatestVersion)
398	prompt = fmt.Sprintf("✨ Update %s → %s", from, to)
399
400	notes := strings.TrimSpace(state.ReleaseNotes)
401	if notes == "" {
402		notes = "(No release notes on GitHub for this release.)"
403	}
404
405	if forRofi {
406		var b strings.Builder
407		title := state.ReleaseName
408		if title == "" {
409			title = "Curd " + to
410		}
411		b.WriteString(`<span foreground="#7CFC98" size="large"><b>🚀 ` + escapePango(title) + `</b></span>` + "\n")
412		b.WriteString(`<span foreground="#E6E6FA">Current </span>`)
413		b.WriteString(`<span foreground="#FF8A80"><b>` + escapePango(from) + `</b></span>`)
414		b.WriteString(`<span foreground="#E6E6FA">  →  Latest </span>`)
415		b.WriteString(`<span foreground="#7CFC98"><b>` + escapePango(to) + `</b></span>` + "\n")
416		if state.HTMLURL != "" {
417			b.WriteString(`<span foreground="#6EC6FF" underline="single">` + escapePango(state.HTMLURL) + `</span>` + "\n")
418		}
419		b.WriteString("\n")
420		b.WriteString(markdownToPango(notes))
421		message = strings.TrimSpace(b.String())
422		// Pango is verbose; soft-cap markup length.
423		if len([]rune(message)) > maxReleaseNotesRunes*3 {
424			r := []rune(message)
425			message = string(r[:maxReleaseNotesRunes*3]) + "\n<span foreground=\"#9A9A9A\">… (truncated — full notes on GitHub)</span>"
426		}
427		return prompt, message
428	}
429
430	// CLI / terminal
431	title := lipgloss.NewStyle().Foreground(lipgloss.Color("#7CFC98")).Bold(true)
432	label := lipgloss.NewStyle().Foreground(lipgloss.Color("#E6E6FA"))
433	oldV := lipgloss.NewStyle().Foreground(lipgloss.Color("#FF8A80")).Bold(true)
434	newV := lipgloss.NewStyle().Foreground(lipgloss.Color("#7CFC98")).Bold(true)
435	link := lipgloss.NewStyle().Foreground(lipgloss.Color("#6EC6FF")).Underline(true)
436
437	var b strings.Builder
438	name := state.ReleaseName
439	if name == "" {
440		name = "Curd " + to
441	}
442	b.WriteString(title.Render("🚀 "+name) + "\n")
443	b.WriteString(label.Render("Current ") + oldV.Render(from) + label.Render("  →  Latest ") + newV.Render(to) + "\n")
444	if state.HTMLURL != "" {
445		b.WriteString(link.Render(state.HTMLURL) + "\n")
446	}
447	b.WriteString("\n")
448	b.WriteString(markdownToTerminal(notes))
449	message = strings.TrimSpace(b.String())
450	// Cap plain-ish length for terminal
451	plain := ansiStrip.ReplaceAllString(message, "")
452	if len([]rune(plain)) > maxReleaseNotesRunes {
453		// Keep header + truncated notes roughly
454		message = message + "\n" + label.Render("… (truncated — full notes on GitHub)")
455	}
456	return prompt, message
457}
458
459func updateActionOptions() []SelectionOption {
460	// Emoji prefixes: lively, ordered, no numeric indices; preserveOrder keeps this order.
461	return []SelectionOption{
462		{Key: "update", Label: "🚀  Update now"},
463		{Key: "later", Label: "⏰  Remind me later"},
464		{Key: "skip", Label: "⏭️  Skip this version"},
465		{Key: "disable", Label: "🔕  Turn off automatic update checks"},
466		{Key: "continue", Label: "▶️  Continue without updating"},
467	}
468}
469
470// refreshUpdateStateFromGitHub reloads tag/name/body/url from the live release API
471// so the prompt shows real markdown notes instead of a stale/test seed.
472func refreshUpdateStateFromGitHub(state *updatePendingState) {
473	if state == nil {
474		return
475	}
476	release, err := fetchLatestGitHubRelease(defaultUpdateRepo)
477	if err != nil {
478		Log(fmt.Sprintf("Could not refresh release notes from GitHub: %v", err))
479		return
480	}
481	latest := normalizeReleaseVersion(release.TagName)
482	if latest == "" {
483		return
484	}
485	// If GitHub moved past what we flagged, still show the newest release.
486	state.LatestTag = release.TagName
487	state.LatestVersion = latest
488	state.ReleaseName = strings.TrimSpace(release.Name)
489	if state.ReleaseName == "" {
490		state.ReleaseName = "Curd " + latest
491	}
492	// Full markdown body from the GitHub release page (API `body` field).
493	// Do not seed/test stubs here — always prefer live API content when online.
494	state.ReleaseNotes = strings.TrimSpace(release.Body)
495	state.HTMLURL = release.HTMLURL
496	state.CheckedAt = time.Now().UTC().Format(time.RFC3339)
497	if asset, assetErr := curdReleaseBinaryName(); assetErr == nil {
498		state.AssetName = asset
499	}
500	state.Available = true
501}
502
503// updateUserMessage prints a single status line. With Rofi mode, CurdOut becomes
504// notify-send — so we only send one short notification (or log) for status.
505func updateUserMessage(config *CurdConfig, msg string) {
506	msg = strings.TrimSpace(msg)
507	if msg == "" {
508		return
509	}
510	Log(msg)
511	if config != nil && config.RofiSelection {
512		// One short desktop notification, not a barrage of CurdOut lines.
513		_ = exec.Command("notify-send", "-a", "Curd",
514			"-h", "string:x-canonical-private-synchronous:curd-update",
515			"Curd", msg).Run()
516		return
517	}
518	fmt.Println(msg)
519}
520
521// HandlePendingUpdatePrompt shows a previously detected update (from idle check).
522// Returns true if the caller should exit (user updated or chose to quit the session).
523func HandlePendingUpdatePrompt(config *CurdConfig, currentVersion string) bool {
524	if config == nil || !config.CheckUpdates {
525		return false
526	}
527	state := loadUpdatePendingState(config.StoragePath)
528	if !pendingUpdateShouldPrompt(config, currentVersion, state) {
529		return false
530	}
531
532	// Pull live release markdown from GitHub so notes match the release page.
533	refreshUpdateStateFromGitHub(&state)
534	if !pendingUpdateShouldPrompt(config, currentVersion, state) {
535		// e.g. already up to date after refresh
536		state.Available = false
537		_ = saveUpdatePendingState(config.StoragePath, state)
538		return false
539	}
540	_ = saveUpdatePendingState(config.StoragePath, state)
541
542	// Fixed order (Update now first). Emoji labels; preserveOrder for CLI.
543	options := updateActionOptions()
544	prompt, message := buildUpdatePromptMessageMode(currentVersion, state, config.RofiSelection)
545
546	var selected SelectionOption
547	var err error
548	if config.RofiSelection {
549		// Pango-colored notes in -mesg; one Rofi UI, no notify spam.
550		selected, err = RofiSelectWithMessage(options, false, prompt, message)
551	} else {
552		header := lipgloss.NewStyle().Foreground(lipgloss.Color("#FFD166")).Bold(true)
553		fmt.Println(header.Render(prompt))
554		fmt.Println(message)
555		fmt.Println()
556		selected, err = promptSelectOrdered(options)
557	}
558	if err != nil {
559		return false
560	}
561	selected = NormalizeSelectionKey(selected)
562	// Quit from the pinned menu must exit the whole program (not fall through to curd).
563	if SelectionMeansQuit(selected) {
564		ExitCurd(nil)
565		return true
566	}
567	// Back / empty = dismiss update prompt and continue the session.
568	if SelectionMeansBack(selected) || selected.Key == "continue" || selected.Key == "" {
569		return false
570	}
571
572	switch selected.Key {
573	case "update":
574		updateUserMessage(config, "Downloading and installing update…")
575		if err := UpdateCurd(defaultUpdateRepo, "curd"); err != nil {
576			updateUserMessage(config, fmt.Sprintf("Update failed: %v", err))
577			Log(fmt.Sprintf("Update failed: %v", err))
578			return false
579		}
580		state.Available = false
581		state.RemindAfter = ""
582		_ = saveUpdatePendingState(config.StoragePath, state)
583		updateUserMessage(config, fmt.Sprintf("Updated to %s. Please restart curd.", state.LatestVersion))
584		return true
585	case "later":
586		until := time.Now().Add(defaultRemindLaterDuration)
587		state.RemindAfter = until.UTC().Format(time.RFC3339)
588		state.Available = true
589		_ = saveUpdatePendingState(config.StoragePath, state)
590		updateUserMessage(config, fmt.Sprintf("Will remind again after %s.", formatLocalTime(until)))
591		return false
592	case "skip":
593		state.SkippedVersion = state.LatestVersion
594		state.Available = false
595		state.RemindAfter = ""
596		_ = saveUpdatePendingState(config.StoragePath, state)
597		updateUserMessage(config, fmt.Sprintf("Skipping version %s.", state.LatestVersion))
598		return false
599	case "disable":
600		if err := setConfigBoolOption(GlobalConfigPath, "CheckUpdates", false); err != nil {
601			updateUserMessage(config, fmt.Sprintf("Could not write config: %v", err))
602			Log(fmt.Sprintf("disable CheckUpdates: %v", err))
603		} else {
604			config.CheckUpdates = false
605			updateUserMessage(config, "Automatic update checks disabled (CheckUpdates=false).")
606		}
607		state.Available = false
608		_ = saveUpdatePendingState(config.StoragePath, state)
609		return false
610	default:
611		return false
612	}
613}
614
615func setConfigBoolOption(configPath, key string, value bool) error {
616	if strings.TrimSpace(configPath) == "" {
617		return fmt.Errorf("config path is empty")
618	}
619	configMap, err := LoadConfigFromFile(configPath)
620	if err != nil {
621		return err
622	}
623	_, existed := configMap[key]
624	if value {
625		configMap[key] = "true"
626	} else {
627		configMap[key] = "false"
628	}
629	if !existed {
630		return appendConfigKeys(configPath, configMap, []string{key})
631	}
632	return SaveConfigToFile(configPath, configMap)
633}
634
635func isPermissionError(err error) bool {
636	if err == nil {
637		return false
638	}
639	if errors.Is(err, os.ErrPermission) {
640		return true
641	}
642	msg := strings.ToLower(err.Error())
643	return strings.Contains(msg, "permission denied") ||
644		strings.Contains(msg, "access is denied") ||
645		strings.Contains(msg, "operation not permitted")
646}
647
648// isCrossDeviceError reports rename/link failures when src and dest are on
649// different filesystems (e.g. /tmp tmpfs → ~/.local/bin on disk).
650func isCrossDeviceError(err error) bool {
651	if err == nil {
652		return false
653	}
654	var linkErr *os.LinkError
655	if errors.As(err, &linkErr) {
656		err = linkErr.Err
657	}
658	msg := strings.ToLower(err.Error())
659	return strings.Contains(msg, "cross-device") ||
660		strings.Contains(msg, "cross device") ||
661		strings.Contains(msg, "exdev") ||
662		strings.Contains(msg, "invalid cross-device link")
663}
664
665func hasDisplay() bool {
666	return os.Getenv("DISPLAY") != "" || os.Getenv("WAYLAND_DISPLAY") != ""
667}
668
669func stdinIsTerminal() bool {
670	return term.IsTerminal(int(os.Stdin.Fd()))
671}
672
673// preferGUIPasswordPrompt decides whether to open a desktop password dialog.
674//
675//   - Rofi/desktop mode → GUI first (zenity/yad/kdialog)
676//   - Plain CLI with a TTY (e.g. `curd -u` in a terminal) → terminal only
677//   - No TTY but a display → GUI
678func preferGUIPasswordPrompt() bool {
679	rofi := false
680	if cfg := GetGlobalConfig(); cfg != nil {
681		rofi = cfg.RofiSelection
682	}
683	tty := stdinIsTerminal()
684
685	// Interactive CLI: never pop a GUI dialog just because DISPLAY is set.
686	if tty && !rofi {
687		return false
688	}
689	if rofi {
690		return true
691	}
692	// Headless of TTY (desktop launcher without a terminal): GUI if available.
693	return !tty && hasDisplay()
694}
695
696// promptSudoPasswordGUI tries GTK/desktop password dialogs (zenity → yad → kdialog).
697func promptSudoPasswordGUI(prompt string) (string, error) {
698	if prompt == "" {
699		prompt = "Enter your password to install the Curd update:"
700	}
701
702	type dialog struct {
703		name string
704		args []string
705	}
706	dialogs := []dialog{
707		// GTK (GNOME / many desktops)
708		{"zenity", []string{"--password", "--title=Curd Update", "--text=" + prompt}},
709		// GTK-based yad
710		{"yad", []string{"--entry", "--hide-text", "--title=Curd Update", "--text=" + prompt, "--button=OK:0", "--button=Cancel:1"}},
711		// KDE
712		{"kdialog", []string{"--title", "Curd Update", "--password", prompt}},
713	}
714
715	for _, d := range dialogs {
716		bin, err := exec.LookPath(d.name)
717		if err != nil {
718			continue
719		}
720		cmd := exec.Command(bin, d.args...)
721		out, err := cmd.Output()
722		if err != nil {
723			// User cancel or dialog error — try next tool only on "not found"; cancel stops.
724			var exitErr *exec.ExitError
725			if errors.As(err, &exitErr) {
726				// zenity/yad/kdialog: non-zero usually means cancel.
727				return "", fmt.Errorf("password dialog cancelled")
728			}
729			Log(fmt.Sprintf("password dialog %s failed: %v", d.name, err))
730			continue
731		}
732		password := strings.TrimRight(string(out), "\r\n")
733		if password == "" {
734			return "", fmt.Errorf("empty password")
735		}
736		Log(fmt.Sprintf("Collected sudo password via %s dialog", d.name))
737		return password, nil
738	}
739	return "", fmt.Errorf("no GUI password dialog available (tried zenity, yad, kdialog)")
740}
741
742func promptSudoPassword(prompt string) (string, error) {
743	if prompt == "" {
744		prompt = "Administrator password (sudo) to install update: "
745	}
746
747	rofi := false
748	if cfg := GetGlobalConfig(); cfg != nil {
749		rofi = cfg.RofiSelection
750	}
751	tty := stdinIsTerminal()
752
753	// Rofi/desktop: try zenity/yad/kdialog first.
754	if preferGUIPasswordPrompt() {
755		if password, err := promptSudoPasswordGUI(prompt); err == nil {
756			return password, nil
757		} else {
758			Log(fmt.Sprintf("GUI password prompt unavailable (%v)", err))
759			// Explicit cancel in GUI: only abort if we shouldn't fall back to TTY.
760			// In rofi mode with no TTY, cancel means cancel.
761			if strings.Contains(err.Error(), "cancelled") && (!tty || rofi) {
762				// If we still have a real terminal under us (rare with rofi), allow TTY
763				// fallback only when not in rofi mode.
764				if !tty {
765					return "", err
766				}
767				if rofi {
768					// Rofi session: user closed the dialog on purpose.
769					return "", err
770				}
771			}
772			// GUI missing/failed → fall through to terminal when possible.
773		}
774	}
775
776	// Terminal path (CLI `curd -u`, or GUI unavailable).
777	if !tty {
778		return "", fmt.Errorf("no terminal available for password entry; install zenity/yad/kdialog for a GUI prompt")
779	}
780	fmt.Fprint(os.Stderr, prompt)
781	if !strings.HasSuffix(prompt, " ") {
782		fmt.Fprint(os.Stderr, " ")
783	}
784	password, err := term.ReadPassword(int(os.Stdin.Fd()))
785	fmt.Fprintln(os.Stderr)
786	if err != nil {
787		return "", err
788	}
789	return string(password), nil
790}
791
792func installExecutableWithSudo(src, dest string) error {
793	// Prefer install(1) for mode bits; fall back to cp + chmod.
794	password, err := promptSudoPassword("Administrator password (sudo) to install update: ")
795	if err != nil {
796		return fmt.Errorf("read sudo password: %w", err)
797	}
798	if strings.TrimSpace(password) == "" {
799		return fmt.Errorf("empty sudo password")
800	}
801
802	try := func(name string, args ...string) error {
803		cmd := exec.Command(name, args...)
804		cmd.Stdin = strings.NewReader(password + "\n")
805		cmd.Stdout = os.Stdout
806		cmd.Stderr = os.Stderr
807		return cmd.Run()
808	}
809
810	// -S: read password from stdin; -p '': no extra prompt
811	if err := try("sudo", "-S", "-p", "", "install", "-m", "755", src, dest); err == nil {
812		return nil
813	} else {
814		Log(fmt.Sprintf("sudo install failed: %v", err))
815	}
816	if err := try("sudo", "-S", "-p", "", "cp", src, dest); err != nil {
817		return fmt.Errorf("sudo install failed: %w", err)
818	}
819	_ = try("sudo", "-S", "-p", "", "chmod", "755", dest)
820	return nil
821}
822
823// createUpdateTempFile prefers a sibling of the executable (same FS as install
824// path). Falls back to os.TempDir when the install directory is not writable.
825func createUpdateTempFile(executablePath, binaryName string) (string, *os.File, error) {
826	dir := filepath.Dir(executablePath)
827	// Try same directory first for atomic rename.
828	if f, err := os.CreateTemp(dir, ".curd-download-*"); err == nil {
829		return f.Name(), f, nil
830	}
831	// Fall back to system temp (may be cross-device; replaceExecutable handles that).
832	name := "curd-update-" + binaryName
833	if binaryName == "" {
834		name = "curd-update-bin"
835	}
836	path := filepath.Join(os.TempDir(), name)
837	f, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0755)
838	if err != nil {
839		return "", nil, err
840	}
841	return path, f, nil
842}
843
844func copyFileReplace(src, dst string) error {
845	in, err := os.Open(src)
846	if err != nil {
847		return err
848	}
849	defer in.Close()
850
851	// Write to a sibling temp on the destination filesystem, then rename into place.
852	dir := filepath.Dir(dst)
853	tmp, err := os.CreateTemp(dir, ".curd-update-*")
854	if err != nil {
855		return err
856	}
857	tmpName := tmp.Name()
858	cleanup := true
859	defer func() {
860		if cleanup {
861			_ = os.Remove(tmpName)
862		}
863	}()
864
865	if err := tmp.Chmod(0755); err != nil {
866		_ = tmp.Close()
867		return err
868	}
869	if _, err := io.Copy(tmp, in); err != nil {
870		_ = tmp.Close()
871		return err
872	}
873	if err := tmp.Sync(); err != nil {
874		_ = tmp.Close()
875		return err
876	}
877	if err := tmp.Close(); err != nil {
878		return err
879	}
880
881	// Atomic replace when possible (same directory = same filesystem).
882	if err := os.Rename(tmpName, dst); err != nil {
883		// Windows / busy binary: move dest aside first.
884		oldPath := dst + ".old"
885		_ = os.Remove(oldPath)
886		if renOld := os.Rename(dst, oldPath); renOld != nil && !os.IsNotExist(renOld) {
887			return renOld
888		}
889		if renNew := os.Rename(tmpName, dst); renNew != nil {
890			_ = os.Rename(oldPath, dst)
891			return renNew
892		}
893		_ = os.Remove(oldPath)
894	}
895	cleanup = false
896	return nil
897}
898
899// replaceExecutable installs the downloaded binary over the running executable.
900// Handles: same-FS rename, cross-device copy, busy binary swap, and sudo when needed.
901func replaceExecutable(tmpPath, executablePath string) error {
902	// 1) Fast path: rename when both paths share a filesystem.
903	if err := os.Rename(tmpPath, executablePath); err == nil {
904		return nil
905	} else if isPermissionError(err) {
906		updateUserMessage(GetGlobalConfig(), "Update needs elevated permissions to replace the installed binary.")
907		if sudoErr := installExecutableWithSudo(tmpPath, executablePath); sudoErr != nil {
908			return sudoErr
909		}
910		_ = os.Remove(tmpPath)
911		return nil
912	} else if !isCrossDeviceError(err) {
913		// Unexpected rename failure — still try copy-into-place before giving up.
914		Log(fmt.Sprintf("rename to %s failed (%v); trying copy replace", executablePath, err))
915	}
916
917	// 2) Cross-device (or other rename failure): copy onto dest filesystem then swap.
918	if err := copyFileReplace(tmpPath, executablePath); err == nil {
919		_ = os.Remove(tmpPath)
920		return nil
921	} else if isPermissionError(err) {
922		updateUserMessage(GetGlobalConfig(), "Update needs elevated permissions to replace the installed binary.")
923		if sudoErr := installExecutableWithSudo(tmpPath, executablePath); sudoErr != nil {
924			return fmt.Errorf("failed to replace executable: %w", sudoErr)
925		}
926		_ = os.Remove(tmpPath)
927		return nil
928	} else {
929		// Last resort: sudo install from original temp (covers weird FS layouts).
930		if isCrossDeviceError(err) || runtime.GOOS != "windows" {
931			Log(fmt.Sprintf("copy replace failed (%v); trying sudo", err))
932			updateUserMessage(GetGlobalConfig(), "Update needs elevated permissions to replace the installed binary.")
933			if sudoErr := installExecutableWithSudo(tmpPath, executablePath); sudoErr == nil {
934				_ = os.Remove(tmpPath)
935				return nil
936			}
937		}
938		return fmt.Errorf("failed to replace executable: %w", err)
939	}
940}