#!/usr/bin/env sh
#
# ---
# source: https://github.com/bew/dotfiles

progname=$(basename "$0")

usage() {
  cat <<EOF
Usage: ${progname} [-h|--help] [<FG-BG-COLOR>...] [<TEXT-STYLE>...]

<FG-BG-COLOR> can be any number of:
  fg:<COLOR-ID> - foreground text color (COLOR-ID in 1 -> 256)
  bg:<COLOR-ID> - background color (COLOR-ID in 1 -> 256)

<TEXT-STYLE> can be any number of:
  bold     - bold text
  dim      - dim text, thinner font
  italic   - italic text
  under*   - underlined text
  blink    - blinking text
  strike*  - striked-through text

Examples:
  ${progname} bg:33 fg:254 bold italic
  ${progname} fg:107 under

EOF
}

RESET="\e[0m"

# defaults to the terminal default colors & style
TEXT_COLOR=""
TEXT_STYLE=""
# string=$(echo "${string_after}" \
#   | awk '{ string=substr($0, 1, 3); print string; }')
# string=$(echo "${string}" | awk -v var="${stringlen}" \
#   '{ string=substr($0, 1, var - 1); print string; }')

while [ -n "${1:-}" ]; do
  case "$1" in
    fg:*)
      # TEXT_COLOR+="\e[38;5;${1:3}m" # support 256 colors
      # TEXT_COLOR="${TEXT_COLOR}\e[38;5;${1:3}m" # support 256 colors
      TEXT_COLOR="${TEXT_COLOR}\e[38;5;${1#???}m" # support 256 colors
      shift
      ;;
    bg:*)
      # TEXT_COLOR+="\e[48;5;${1:3}m" # support 256 colors
      # TEXT_COLOR="${TEXT_COLOR}\e[48;5;${1:3}m" # support 256 colors
      TEXT_COLOR="${TEXT_COLOR}\e[48;5;${1#???}m" # support 256 colors
      shift
      ;;
    bold)
      TEXT_STYLE="${TEXT_STYLE}\e[1m"
      shift
      ;;
    dim)
      TEXT_STYLE="${TEXT_STYLE}\e[2m"
      shift
      ;;
    italic)
      TEXT_STYLE="${TEXT_STYLE}\e[3m"
      shift
      ;;
    under*)
      TEXT_STYLE="${TEXT_STYLE}\e[4m"
      shift
      ;;
    blink)
      TEXT_STYLE="${TEXT_STYLE}\e[5m"
      shift
      ;;
    strike*)
      TEXT_STYLE="${TEXT_STYLE}\e[9m"
      shift
      ;;
    -h | --help)
      usage
      exit 0
      ;;
    *)
      >&2 echo "ERROR: unknown argument '$1'"
      >&2 usage
      exit 1
      ;;
  esac
done

colored_echo() {
  printf '%b' "${TEXT_COLOR}"
  printf '%b' "$*"
  printf '%b' "${RESET}"
  echo # the only new line
}

echo "---------------------------------"
colored_echo "                                 "
colored_echo "    ${TEXT_STYLE}This is an (example[TXT])${RESET}${TEXT_COLOR}    "
colored_echo "                                 "
echo "---------------------------------"
