#!/usr/bin/env bash

#-------------------------------------------------------------------------------
#
#  is_flag - infer whether or not a command-line argument is a flag OR empty
#
#    returns 0: arg is flag
#    returns 1: arg is not a flag, not empty
#    returns 2: arg is empty
#
#  sources:
#    https://stackoverflow.com/a/10218528/2925434
#    https://stackoverflow.com/a/17287097/2925434
#
#-------------------------------------------------------------------------------

function is_flag {

  local arg=""
  local retval=1

  # if is empty, not a flag
  if [[ -z "$1" ]]; then
    arg="\"\""
    retval=2

  else

    # get first and last characters
    local firstchar="${1:0:1}"
    local lastchar="${1: -1}"
    local short="$1"

    # if surrounded by quotes, remove them
    if [[ $firstchar == "\"" && $lastchar == "\"" ]] ||
       [[ $firstchar == "'"  && $lastchar == "'" ]]; then

      local lenm2=$((${#1}-2))
      short="${1:1:$lenm2}"
    fi

    # if is empty, not a flag
    if [[ -z "$short" ]]; then
      arg="\"\"\"\""
      retval=2

    # if contains spaces, not a flag -- surround with quotes
    elif [[ "$short" = *[[:space:]]* ]]; then
      arg="\"$short\""

    # else, if starts with "-", is a flag -- no quotes
    elif [[ "${short:0:1}" == "-" ]]; then
      arg="$short"
      retval=0

    # else, isn't a flag -- surround with quotes
    else
      arg="\"$short\""
    fi

  fi

  # print arg and return
  echo "${arg}"
  return $retval

}

# usage:
#
#   $ is_flag p        # not a flag, surrounded in quotes
#   "p"
#
#   $ is_flag -p       # is a flag, not surrounded in quotes
#   -p
#
#   $ is_flag "-p"     # is a flag, even though surrounded by quotes
#   -p
#
#   $ is_flag --p      # is a flag, any number of - allowed
#   --p
#
#   $ is_flag "-p a"   # not a flag, because quoted and contains spaces
#   "-p a"
#
#   $ is_flag "-pa"    # is a flag, because contains no spaces
#   -pa
#
#   $ is_flag          # no argument given, return empty string
#   ""
#
#   $ is_flag ""       # empty string given, return empty string
#   ""
#
#   $ is_flag "\"\""   # empty quoted string, return same
#   """"