#!/usr/bin/env bash

set -euo pipefail

# Ensure in a interactive terminal
[ ! -t 0 ] && exit 1

# Construct query
QUERY_CODE=$(printf "\033]1337;ReportCellSize\a")
EXPECTED_RESPONSE=$(printf "\033]1337;") # followed by "ReportCellSize=...", but only the prefix is enough
# Construct fence code that most terminals will respond to
# to ensure that at least something will be sent back and
# to detect the end of the response
FENCE_CODE=$(printf "\033[c")

# Set terminal to raw mode
stty_orig=$(stty -g)
trap 'stty "$stty_orig"' EXIT INT TERM HUP
stty -echo -icanon min 1 time 0

printf "%s%s" "$QUERY_CODE" "$FENCE_CODE" > /dev/tty

response=""
ret=1
while true; do
    IFS= read -r -N 1 -t 0.3 char || {
        [ -z "$char" ] && break
    }

    response+="$char"

    if [[ "$response" == *"$EXPECTED_RESPONSE"* ]]; then
        ret=0
        # Keep reading until response is complete to
        # avoid leaving unread data in the terminal
    fi

    if [[ "$response" == *$'\033['*'c' ]]; then
        break
    fi

    if [ ${#response} -gt 1024 ]; then
        break
    fi
done

exit $ret
