#!/bin/sh

# initialize variables needed for parse_options().
set_variables() {
  # colors used for printing only when stdout is a terminal
  if [ -t 1 ]; then
    # green
    color_info="$(tput setaf 2)"
    # blue
    color_usage="$(tput setaf 4)"
    # blue, bold
    # shellcheck disable=SC2312
    color_user_input="$(tput setaf 4)$(tput bold)"
    no_color_stdout="$(tput sgr0)"
  else
    color_info=''
    color_usage=''
    color_user_input=''
    no_color_stdout=''
  fi
  if [ -t 2 ]; then
    # red
    color_err="$(tput setaf 1)"
    # yellow
    color_warn="$(tput setaf 3)"
    color_neutral_stderr="$(tput sgr0)"
  else
    color_err=''
    color_warn=''
    color_neutral_stderr=''
  fi
  # shellcheck disable=SC2034
  readonly color_info color_usage color_user_input no_color_stdout
  readonly color_err color_warn color_neutral_stderr

  # argument defaults
  confirm='yes'
  dry_run='false'
  quiescence=0
  view='false'
}

err_exit() {
  printv '3' '%s\n' "${color_err}[Error] ${*}${color_neutral_stderr}" 1>&2
  exit 1
}

err_help_exit() {
  printf '%s\n' "${color_err}[Error] ${*}${color_neutral_stderr}" 1>&2
  printf "Use '-h' option for more information.\n" 1>&2
  exit 1
}

print_warn() {
  printv '2' '%s\n' "${color_warn}[Warning] ${*}${color_neutral_stderr}" 1>&2
}

# USAGE
#
# parse command line options and set variables accordingly.
parse_options() {
  if [ "${#}" -ne 0 ]; then
    # display usage if first argument contains -help
    if printf '%s' "${1}" | grep -qi '\-help'; then
      usage
      exit 0
    else
      # while getopts ':abc:de:g:hilno:p:qrstuvy' opt; do
      while getopts ':hi:qt' opt; do
        case "${opt}" in
          h)
            usage
            exit 0
            ;;
          i)
            view='true'
            ;;
          q)
            quiescence=$((quiescence + 1))
            ;;
          t)
            confirm='no'
            dry_run='true'
            ;;
          \?)
            err_help_exit "Invalid option: '${OPTARG}'"
            ;;
          :)
            err_help_exit "Option requires an argument: '${OPTARG}'"
            ;;
        esac
      done
    fi
  fi
}
# Print if message is more important than the quiescence specified.
#   $1: importance (should be a non-negative integer)
#   $2: printf format string
#   $3: string to print (only one)
printv() {
  # shellcheck disable=SC2059
  [ "${1}" -ge "${quiescence}" ] && printf "${2}" "${3}" || return 0
}

# printv_info '0' 'global overrides' "${global_override_path}"
# Format and print informational text to terminal.
#   $1 : importance (should be a non-negative integer)
#   $2 : information label
#   $3…: information (all arguments >= 3)
printv_info() {
  importance="${1}"
  shift
  printv "${importance}" '%-19s' "${1}:"
  shift
  printv "${importance}" '%s\n' "${color_info}${*}${no_color_stdout}"
}

set_variables
parse_options "${@}"
# printv '0' '————————————————————————————————————————————\n'
