package setup

import (
	"syscall"
	"unsafe"
)

type termios struct {
	Iflag  uint32
	Oflag  uint32
	Cflag  uint32
	Lflag  uint32
	Cc     [20]byte
	Ispeed uint32
	Ospeed uint32
}

const (
	tcgetattr = 0x5401
	tcsetattr = 0x5402
	TCSAFLUSH = 2
	ECHO      = 0x8
	ICANON    = 0x100
)

func termiosGetState(fd int) (*termios, bool) {
	var state termios
	if _, _, err := syscall.Syscall(syscall.SYS_IOCTL, uintptr(fd), uintptr(tcgetattr), uintptr(unsafe.Pointer(&state))); err != 0 {
		return nil, false
	}
	return &state, true
}

func termiosDisableEcho(fd int) {
	var state termios
	if _, _, err := syscall.Syscall(syscall.SYS_IOCTL, uintptr(fd), uintptr(tcgetattr), uintptr(unsafe.Pointer(&state))); err != 0 {
		return
	}
	state.Lflag &^= ECHO | ICANON
	syscall.Syscall(syscall.SYS_IOCTL, uintptr(fd), uintptr(tcsetattr), uintptr(unsafe.Pointer(&state)))
}

func termiosRestore(fd int, state *termios) {
	syscall.Syscall(syscall.SYS_IOCTL, uintptr(fd), uintptr(tcsetattr), uintptr(unsafe.Pointer(state)))
}