// KEKS/CM -- KEKS-encoded cryptographic messages
// Copyright (C) 2024-2025 Sergey Matveev <stargrave@stargrave.org>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as
// published by the Free Software Foundation, version 3 of the License.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program.  If not, see <http://www.gnu.org/licenses/>.

package encrypted

import (
	"fmt"
	"os"

	"golang.org/x/term"
)

func ReadPasswd(prompt string) (passwd []byte, err error) {
	if raw := os.Getenv("CM_PASSPHRASE"); raw != "" {
		return []byte(raw), nil
	}
	var tty *os.File
	tty, err = os.OpenFile("/dev/tty", os.O_RDWR, 0)
	if err != nil {
		return
	}
	defer tty.Close()
	tty.WriteString(prompt)
	passwd, err = term.ReadPassword(int(tty.Fd()))
	if err != nil {
		return
	}
	// taken from age/cmd/age/tui.go:clearLine
	const (
		CUI = "\033["   // Control Sequence Introducer
		CPL = CUI + "F" // Cursor Previous Line
		EL  = CUI + "K" // Erase in Line
	)
	fmt.Fprintf(tty, "\r\n"+CPL+EL)
	return
}
