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

package term

import (
	
)

type state struct {
	unix.Termios
}

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

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

	 := 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(int(), ioctlWriteTermios, );  != nil {
		return nil,  //nolint:wrapcheck
	}

	return &, nil
}

func ( uintptr,  *State) error {
	var  *unix.Termios
	if  != nil {
		 = &.Termios
	}
	return unix.IoctlSetTermios(int(), ioctlWriteTermios, ) //nolint:wrapcheck
}

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

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

func ( uintptr,  *State) error {
	return unix.IoctlSetTermios(int(), ioctlWriteTermios, &.Termios) //nolint:wrapcheck
}

func ( uintptr) (,  int,  error) {
	,  := unix.IoctlGetWinsize(int(), unix.TIOCGWINSZ)
	if  != nil {
		return 0, 0,  //nolint:wrapcheck
	}
	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(), ) //nolint:wrapcheck
}

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

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

	defer unix.IoctlSetTermios(int(), ioctlWriteTermios, ) //nolint:errcheck

	return readPasswordLine(passwordReader())
}