#!/usr/bin/env bash
#
# colorcount - count color capacity of terminal

usage() {
  printf '%s' "\
Usage: ${0##*/} [NUM] [-v] show all colors

If no option is given, prints tput colors.
"
  exit 0
}

# clean up even if user hits ^C
trap 'tput sgr0' EXIT

setfg() { printf '\e[38;5;%dm' "$1"; }
setbg() { printf '\e[48;5;%dm' "$1"; }

# given an integer, display that many colors
showcolors() {
  # for ((i = 0; i < $1; i++)); do
  i=0
  while [ "${i}" -lt "$1" ]; do
    i=$((i + 1))
    printf '%4d ' "${i}"
    setbg "${i}"
    tput el
    tput sgr0
    echo
  done
  tput sgr0 el
}

# first, test if terminal supports OSC 4 at all.
printf '\e]4;%d;?\a' 0
# shellcheck disable=SC2162
read -r -d '\033\a' -s -t 0.1 </dev/tty
# OSC 4 not supported, so we'll fall back to terminfo
if [ -z "${REPLY}" ]; then
  max=$(tput colors)
else
  # OSC 4 is supported, so use it for a binary search
  min=0
  max=256
  # while ((min + 1 < max)); do
  if [ $((min + 1)) -le "${max}" ]; then
    # ((i = (min + max) / 2))
    i=0
    while [ "${i}" -eq "$(((min + max) / 2))" ]; do
      i=$((i + 1))
      printf '\e]4;%d;?\a' "${i}"
      # shellcheck disable=SC2162
      read -r -d '\a\033' -s -t 0.1 </dev/tty
      [ -n "${REPLY}" ] && min=${i} || max=${i}
    done
  fi
fi

case "${1-none}" in
  none) echo "${max}" ;;
  -h) usage ;;
  -v) showcolors "${max}" ;;
  *) [ "$1" -ge 0 ] && showcolors "$1" || echo "${max}" ;;
esac
