# //  DESCRIPTION:
# //      Utility script to parse input arguments and remove them. It expects that 2 functions
# //      are defined named match_arg_with_value() and match_boolean_arg() which test $1 to see
# //      if it matches an expected argument and return 1 if a match was made and 0 otherwise.
# //      rearg_match_arg_with_value() matches arguments that have 1 value and
# //      rearg_match_boolean_arg() matches arguments that are a single value that is either present
# //      or not. All matched arguments (and their values if applicable) are removed from the
# //      argument list of the script, and unmatched arguments are not. This script should be
# //      called from other scripts with a preceding ". " (dot and space).

# Examples of rearg_match_arg_with_value() and rearg_match_boolean_arg():

#match_arg_with_value()
#{
#  local matched=1
#  case $1 in
#    -profileName)  profile=$2 ;;
#    -startingport) startingport=$2 ;;
#    *)             matched=0  ;;
#  esac
#  return $matched
#}

#match_boolean_arg()
#{
#  local matched=1
#  case $1 in
#    -create)         mode=create ;;
#    -delete)         mode=delete ;;
#    -os400passwords) os400passwords=1 ;;
#    *)               matched=0  ;;
#  esac
#  return $matched
#}


total_args=$# # keep track of the initial argument total, because $# will become meaningless
              # if unmatched arguments are found
arg_num=0     # current index in the initial argument list
while [ $total_args -gt $arg_num ]; do # loop through the initial arguments
  # first test for -<switch> <value> type arguments
  num_args=2 # if an argument is found, we remove 2 arguments (the switch and its value)
  arg_found=1
  if [ $arg_num -lt $(($total_args - 1)) ]; then # make sure there are at least 2 arguments left
    rearg_match_arg_with_value "$1" "$2"
    if [ $? -eq 0 ] ; then
      num_args=1
    fi
  else
    num_args=1
  fi

  # test for -<switch> type arguments if no matches have been found yet
  if [ $num_args -eq 1 ]; then
    rearg_match_boolean_arg "$1"
    if [ $? -eq 0 ] ; then
      arg_found=0 # no arguments were matched
    fi
  fi

  if [ $arg_found -eq 1 ]; then
    # match was made, remove the number of processed arguments
    shift $num_args
  else
    # no match, add the current argument to the end of the argument list
    # this ensures the remaining arguments will be in the same order they were specified
    temp_arg=$1
    shift
    set -- "$@" "$temp_arg"
  fi

  arg_num=$(($arg_num + $num_args)) # increment the current argument index
                                    # by the number of processed arguments
done
