#!/usr/bin/env bash

# Tester for various SGR attributes.
# Copyright (C) 2017  Egmont Koblinger
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

cell=$'Foo▞ \e[32mgrn▞\e[39m \e[45mmgn▞\e[49m \e[58:5:9mred▞\e[59m'

shopt -s extglob
cell_plain="${cell//$'\e['+([^m])m/}"
cell_width=${#cell_plain}

attr_name=(bold dim italic underline underline "double underline" "double underline" "curly underline" blink reverse hidden strikethrough)
attr_start=(  1   2      3         4       4:1                 21                4:2               4:3     5       7      8             9)
attr_end=(   22  22     23        24       4:0                 24                4:0               4:0    25      27     28            29)

col_name=('normal')
col_start=('')
col_end=('')

row_name=('normal')
row_start=('')
row_end=('')

col1_width=6

for (( i = 0; i < ${#attr_name[@]}; i++ )); do
  rn="${attr_name[i]} (${attr_start[i]}/${attr_end[i]})"
  if [ ${#rn} -gt $col1_width ]; then
    col1_width=${#rn}
  fi
  row_name+=("$rn")
  row_start+=($'\e['"${attr_start[i]}m")
  row_end+=($'\e['"${attr_end[i]}m")
done

for arg; do
  for (( i = 0; i < ${#attr_name[@]}; i++ )); do
    if [ "$arg" = "${attr_name[i]}" -o "$arg" = "${attr_start[i]}" ]; then
      col_name+=("${attr_name[i]} (${attr_start[i]}/${attr_end[i]})")
      col_start+=($'\e['"${attr_start[i]}m")
      col_end+=($'\e['"${attr_end[i]}m")
    fi
  done
done


echo "Hint: Specify command line arguments (attribute names or starting numbers)"
echo "to create columns for them. E.g.: ${0##*/} 1 8, or ${0##*/} bold hidden."
echo

echo "green text (32/29)"
echo "magenta background (45/49)"
echo "bright red underline (58:5:9/59)"
echo

printf "%${col1_width}s"
for (( col = 0; col < ${#col_end[@]}; col++ )); do
  echo -n "  "
  printf "%-${cell_width}.${cell_width}s" "${col_name[col]}"
done
echo

for (( row = 0; row < ${#row_end[@]}; row++ )); do
  printf "%-${col1_width}.${col1_width}s  " "${row_name[row]}"
  for (( col = 0; col < ${#col_end[@]}; col++ )); do
    echo -n "${row_start[row]}"
    echo -n "${col_start[col]}"
    echo -n "$cell"
    echo -n "${col_end[col]}"
    echo -n "${row_end[row]}"
    if [ $((col+1)) -lt ${#col_end[@]} ]; then
      echo -n "  "
    fi
  done
  echo
done
