// Copyright 2019 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

//go:build aix || darwin || dragonfly || freebsd || linux || netbsd || openbsd || solaris || zos

package term

import (
	
)

type state struct {
	termios unix.Termios
}

func isTerminal( int) bool {
	,  := unix.IoctlGetTermios(, ioctlReadTermios)
	return  == nil
}

func makeRaw( int) (*State, error) {
	,  := unix.IoctlGetTermios(, ioctlReadTermios)
	if  != nil {
		return nil, 
	}

	 := State{state{termios: *}}

	// This attempts to replicate the behaviour documented for cfmakeraw in
	// the termios(3) manpage.
	.Iflag &^= unix.IGNBRK | unix.BRKINT | unix.PARMRK | unix.ISTRIP | unix.INLCR | unix.IGNCR | unix.ICRNL | unix.IXON
	.Oflag &^= unix.OPOST
	.Lflag &^= unix.ECHO | unix.ECHONL | unix.ICANON | unix.ISIG | unix.IEXTEN
	.Cflag &^= unix.CSIZE | unix.PARENB
	.Cflag |= unix.CS8
	.Cc[unix.VMIN] = 1
	.Cc[unix.VTIME] = 0
	if  := unix.IoctlSetTermios(, ioctlWriteTermios, );  != nil {
		return nil, 
	}

	return &, nil
}

func getState( int) (*State, error) {
	,  := unix.IoctlGetTermios(, ioctlReadTermios)
	if  != nil {
		return nil, 
	}

	return &State{state{termios: *}}, nil
}

func restore( int,  *State) error {
	return unix.IoctlSetTermios(, ioctlWriteTermios, &.termios)
}

func getSize( int) (,  int,  error) {
	,  := unix.IoctlGetWinsize(, unix.TIOCGWINSZ)
	if  != nil {
		return 0, 0, 
	}
	return int(.Col), int(.Row), nil
}

// passwordReader is an io.Reader that reads from a specific file descriptor.
type passwordReader int

func ( passwordReader) ( []byte) (int, error) {
	return unix.Read(int(), )
}

func readPassword( int) ([]byte, error) {
	,  := unix.IoctlGetTermios(, ioctlReadTermios)
	if  != nil {
		return nil, 
	}

	 := *
	.Lflag &^= unix.ECHO
	.Lflag |= unix.ICANON | unix.ISIG
	.Iflag |= unix.ICRNL
	if  := unix.IoctlSetTermios(, ioctlWriteTermios, &);  != nil {
		return nil, 
	}

	defer unix.IoctlSetTermios(, ioctlWriteTermios, )

	return readPasswordLine(passwordReader())
}