cmd/ez-agent-configurator/show_signin_link.go

package main

import (
	"context"
	"errors"
	"io"
)

// Invoked only by the explicit Show link action while tview is suspended.
// Unlike Copy link, this intentionally leaves the URL in terminal scrollback.
var showSignInLink = func(ctx context.Context, link string) error {
	terminal, closeTerminal, err := openSignInTerminal(ctx)
	if err != nil {
		return errors.New("cannot open the terminal")
	}
	defer closeTerminal()
	return printSignInLink(ctx, terminal, link)
}

func printSignInLink(ctx context.Context, terminal io.ReadWriter, link string) error {
	if ctx.Err() != nil {
		return ctx.Err()
	}
	// CRLF handles the temporary no-echo/raw terminal mode. There are no hard
	// wraps, labels or indentation within the URL. Only the terminal soft-wraps.
	text := "\r\nSelect the line below to copy it. It stays in terminal scrollback.\r\n\r\n" + link +
		"\r\n\r\nPress Enter to return. Paste the callback only in the dialog.\r\n"
	if n, err := io.WriteString(terminal, text); err != nil || n != len(text) {
		return errors.New("cannot display the sign-in link")
	}
	var input [1]byte // Never retain a pasted address or echo it in this mode.
	for {
		if ctx.Err() != nil {
			return ctx.Err()
		}
		n, err := terminal.Read(input[:])
		if err != nil {
			if ctx.Err() != nil {
				return ctx.Err()
			}
			return errors.New("cannot wait for the terminal")
		}
		if n == 1 {
			switch input[0] {
			case '\r', '\n':
				return nil
			case 3, 27: // Ctrl+C or Escape cancels the pending login after resume.
				return context.Canceled
			}
		}
	}
}