#!/bin/sh -e

# if '-e' flag is passed, cells will be three rows high
if [ "$1" = "-e" ]; then
  expanded=true
else
  expanded=false
fi

# if option '-16' is given, only show the first 16 colors
if [ "$1" = "-16" ]; then
  # shellcheck disable=SC2034
  showall="true"
  sixteen="true"
  expanded="true"
else
  sixteen=false
fi

# creates a color row
# arguments:
#   - width (number)
#   - starting color (number)
#   - ending color (number)
row() {
  # give the arguments names for scope reasons
  width=$(($1 - 2))
  start=$2
  end=$3

  # creates a "slice" (one terminal row) of a row
  # can be have number labels or be blank
  # arguments:
  #   - label (boolean)
  slice() {
    # for ((i=$start; i<=$end; i++)); do
    i="${start}"
    while [ "${i}" -lt "${end}" ]; do
      i=$((i + 1))
      # determine if there will be a label on this cell:
      # this is actually a per slice setting but the title needs to be
      # set on each cell because of the numbering
      if [ -n "$1" ]; then
        string=${i}
      else
        string=' '
      fi

      # change background to the correct color
      tput setab "${i}"

      # print the cell
      printf "%${width}s " "${string}"
    done

    # clear the coloring to avoid nasty wrapping colors
    tput sgr0
    echo
  }

  if [ "${expanded}" = "true" ]; then
    # print a blank slice, a labeled one, and then a blank one
    slice
    slice true
    slice
  else
    # just print the labeled slice
    slice true
  fi
}

display() {
  # get the widths based on columns
  cols="$(stty </dev/tty size 2>/dev/null | awk '{ print $2 }' || echo "80")"
  sixth=$((cols / 6))
  eighth=$((cols / 8))
  twelfth=$((cols / 12))

  # give it some room to breathe
  echo

  # first sixteen colors
  row "${eighth}" 0 7
  row "${eighth}" 8 15
  echo

  if [ "${sixteen}" = "true" ]; then
    exit
  fi

  # 16-231
  # for ((a=0; a<=35; a++)); do
  a=0
  while [ "${a}" -lt 35 ]; do
    a=$((a + 1))
    row "${sixth}" $((16 + (6 * a))) $((21 + (6 * a)))
  done
  echo

  # greyscale
  row "${twelfth}" 232 243
  tput setaf 0
  row "${twelfth}" 244 255

  # clear before exiting
  tput sgr0
  echo
}

if [ "$1" = "-h" ] || [ "$1" = "--help" ]; then
  printf '%s\n' "Usage: $(basename "$0") [-e] expanded cells [-16] 16 colors"
  exit 0
else
  # show table
  display
fi
