#!/bin/bash

# This script can be sourced so the macros below can be utilised (although
# scope is intentionally limited to the current process) or it can be run.

igconf_tr()
{
   local prefix="$1"
   shift
   local args=()
   local vars=()
   for arg in "$@" ; do
      if [ -n "${prefix}" ]; then
         args+=("${prefix}_${arg}")
      else
         args+=("$arg")
      fi
   done
   for v in "${args[@]}" ; do
      v="${v#IGconf_}"
      vars+=("IGconf_${v,,}")
   done
   if (( ${#vars[@]} )); then
      printf '%s\n' "${vars[@]}"
   fi
}

igconf_isset()
{
   for v in $(igconf_tr "" "$@") ; do
      if [ -z ${!v+x} ]; then
         return 1 # unset
      fi
    done
    return 0
}

igconf_isnset()
{
   for v in $(igconf_tr "" "$@") ; do
      if [ -z ${!v+x} ]; then
         :
      else
         return 1 # set
      fi
    done
    return 0
}

igconf_isy()
{
   igconf_isset "$@" || return 1
   for v in $(igconf_tr "" "$@") ; do
      case ${!v,,} in
         y|yes)
            ;;
      *)
         return 1
         ;;
      esac
   done
   return 0
}

igconf_isn()
{
   igconf_isset "$@" || return 1
   for v in $(igconf_tr "" "$@") ; do
      case ${!v,,} in
         n|no)
            ;;
      *)
         return 1
         ;;
      esac
   done
   return 0
}

igconf_isval()
{
   igconf_isset "$@" || return 1
   for v in $(igconf_tr "" "$@") ; do
      if [ -z "${!v}" ]; then
         return 1 # empty
      fi
    done
    return 0
}

igconf_getval()
{
   igconf_isval "$@" || return 1
   local v values=()
   for v in $(igconf_tr "" "$@"); do
      values+=("${!v}")
   done
   printf '%s\n' "${values[*]}"
}

if [[ "${BASH_SOURCE[0]}" == "${0}" ]] ; then
   set -u

   [[ $# -lt 1 ]] && exit 1

   op="$1"
   shift 1

   case "$op" in
      isy|isn|isset|isnset|isval|getval)
         igconf_"$op" "$@"
         exit $?
         ;;
      *)
         >&2 echo "Error: invalid igconf op ($op) args: $@" ; exit 1
         ;;
   esac
   exit 1
fi
