#!/bin/sh
#
# Test the behaviour of the shell's builtin `getopts`
#

#:
#: Reset all the global variables thar are used by `getopts`
#:
#: Output (Globals):
#:   OPTIND (int):
#:   OPTARG:
#:
reset_getopts() {
    OPTIND=1
    OPTARG=
    # XXX FIXME: Is this used in FreeBSD's /bin/sh
    # OPTERR=

    # The test variable
    opt=''
    
    return 0
}


test_standard_1() {
    while getopts 'ab:' opt; do
        case "$opt" in
            a)
                echo "OPTION: a with arg: \`${OPTARG+SET}'"
                ;;
            b)
                echo "OPTION: b with arg: \`${OPTARG}'"
                ;;
            \?)
		# All errors are reported here
                if [ -n "${OPTARG+SET}" ] ; then
                    echo "ERROR: unknown option: ${OPTARG}" >&2
                else
		    echo "ERROR: unknown option" >&2
		fi
                ;;
	    :)
		# Never landing here
                if [ -n "${OPTARG+SET}" ] ; then
                    echo "ERROR: unknown option (colon): ${OPTARG}" >&2
                else
		    echo "ERROR: unknown option (colon)" >&2
		fi
                ;;
            *)
                echo "ERROR: option handling" >&2
                ;;
        esac
    done
    echo "OPTIND: ${OPTIND}"
}


#:
#: Silent mode with a colon ``:`` as the first character in optstring.
#:
#: This is undocumented in current FreeBSD's :command:`/bin/sh`.
#: But it works as in :command:`/usr/local/bin/ksh93`.
#:
test_noreport_1() {
    # Note: The first char in optstring is a colon!
    while getopts ':ab:' opt; do
        case "$opt" in
            a)
                echo "OPTION: a with arg: \`${OPTARG+SET}'"
                ;;
            b)
                echo "OPTION: b with arg: \`${OPTARG}'"
                ;;
            \?)
		# An invalid option is reported here
                if [ -n "${OPTARG+SET}" ] ; then
                    echo "ERROR: unknown option: ${OPTARG}" >&2
                else
		    echo "ERROR: unknown option" >&2
		fi
                ;;
	    :)
		# A missing required parameter is reported here
                if [ -n "${OPTARG+SET}" ] ; then
                    echo "ERROR: unknown option (colon): ${OPTARG}" >&2
                else
		    echo "ERROR: unknown option (colon)" >&2
		fi
                ;;
            *)
                echo "ERROR: option handling" >&2
                ;;
        esac
    done
    echo "OPTIND: ${OPTIND}"    
}
