#!/bin/bash

################################################################################
# Functions
################################################################################

padding="   " # three digits of whitespace padding

print_index () {
  index=$1
  printf "%s%s" "${padding:${#index}}" " $index "
}

lut="\e[48;5;"      # ANSI escape code prefix for the color lookup table (LUT)
reset="\e[0;39;49m" # ANSI escape code to restore defaults

print_color () {
  index=$1
  printf "${lut}${index}m ${padding} ${reset}"
}

################################################################################
# Main
################################################################################

bold="\e[1m" # ANSI escape code for bold text

# Standard colors

printf "\n${bold}Standard colors${reset}\n\n"
for (( n=0; n<8; n+=1 )) ; do
  print_index $n
  print_color $n
done

# Bright colors

printf "\n\n${bold}Bright colors${reset}\n\n"
for (( n=8; n<16; n+=1 )) ; do
  print_index $n
  print_color $n
done

# Colors #16-231

printf "\n\n${bold}Colors #16-231${reset}\n"
for (( n=16; n<232; n+=6 )) ; do
  (( (n-16) % 36 )) || echo ""  # Extra space between each 6x6 block of colors

  for i in {0..5}; do
    print_index $(( n+i ))
    print_color $(( n+i ))
  done

  echo ""
done

# Grayscale colors

printf "\n${bold}Grayscale colors${reset}\n\n"
for (( n=232; n<255; n+=6 )) ; do
  for i in {0..5}; do
    print_index $(( n+i ))
    print_color $(( n+i ))
  done

  echo ""
done

echo ""