# shellcheck shell=dash disable=SC2034
___x_cmd_tty___main(){
    [ "$#" -gt 0 ] || {
        ___x_cmd_tty_which
        return
    }

    local op="$1";      shift
    case "$op" in
        col)            printf "%s\n" "$COLUMNS"  ;;
        row)            printf "%s\n" "$LINES"    ;;
        update)         ___x_cmd_tty_update_lines_columns ;;
        stdin|stdin_|\
        which|which_)
                        "___x_cmd_tty_${op}" "$@" ;;

        -h|--help)      ___x_cmd help -m tty    ;;
        *)              N=tty M="unknwon subcmd ==> $op" log:ret:64 ;;
    esac
}

___X_CMD_TTY_STDIN_=/dev/tty

___x_cmd_tty_stdin_(){
    :
}

# if [ -d /proc/$$ ]; then
#     ___x_cmd_tty_stdin_(){
#         [ -z "$___X_CMD_TTY_STDIN_" ] || return 0
#         ___X_CMD_TTY_STDIN_="/proc/$$/fd/0"
#     }

#     # Alpine:
#     # ps -o tty,pid | awk -v pid="$$" '$2==pid{ print $1; }'
# else
#     ___x_cmd_tty_stdin_(){
#         [ -z "$___X_CMD_TTY_STDIN_" ] || return 0
#         ___X_CMD_TTY_STDIN_=$(command ps -o pid,tty | command awk -v pid=$$ '$1==pid{ print "/dev/" $2; exit(0) }')
#     }
# fi

___X_CMD_TTY_WHICH=""
___x_cmd_tty_which(){
    local x_
    ___x_cmd_tty_which_ || return
    printf "%s\n" "$x_"
}

___x_cmd_tty_which_(){
    if [ -z "$___X_CMD_TTY_WHICH" ]; then
        ___X_CMD_TTY_WHICH="$(___x_cmd_cmds tty)"
    fi
    x_="$(___x_cmd_cmds tty)"
    ___X_CMD_TTY_WHICH="$x_"
}

___x_cmd_tty_stdin(){
    ___x_cmd_tty_stdin_
    printf "%s\n" "$___X_CMD_TTY_STDIN_"
}

# Thank ryenus, iRaS and Mekcki for answers in https://stackoverflow.com/questions/263890/how-do-i-find-the-width-height-of-a-terminal-window
# TODO: this line results in terrible performance issue ( 100ms ):  ___x_cmd_compat_syncfs "$___X_CMD_TTY_STDIN_"
# if [ -z "${LINES}${COLUMNS}" ] && [ -e "$___X_CMD_TTY_STDIN_" ]; then
if [ -z "${LINES}${COLUMNS}" ] && ___x_cmd_compat_syncfs "$___X_CMD_TTY_STDIN_" 2>/dev/null; then
    ___X_CMD_TTY_ROWCOL_MANUAL_REFRESH_REQUIRED=1
    ___x_cmd_tty_stdin_

    ___x_cmd_tty_update_lines_columns(){
        local IFS
        IFS=" "
        read -r LINES COLUMNS <<A
$(command stty size <"$___X_CMD_TTY_STDIN_" 2>/dev/null)
A
    }
    ___x_cmd_tty_update_lines_columns
else
    ___x_cmd_tty_update_lines_columns(){ :; }
fi
