#!/bin/sh
#
# SPDX-License-Identifier: BSD-2-Clause
#
# Copyright (c) 2010-2026 Devin Teske
#
############################################################ INCLUDES

SYSRC_SHARE="/usr/share/sysrc"
[ "$_SYSRC_SUBR" ] || . $SYSRC_SHARE/sysrc.subr || exit 1

############################################################ GLOBALS

pgm="${0##*/}" # Program basename

#
# Version information
#
SYSRC_VERSION="9.3 Nov-18,2026"

#
# Options
#
CHECK_ONLY=		# -c
DEFAULT=		# -D
DELETE=			# -x / -X
DESCRIBE=		# -d
EXISTING_ONLY=		# -E
IGNORE_UNKNOWNS=	# -i
JAIL=			# -j jail
LIST_CONFS=		# -l
LIST_SERVICE_CONFS=	# -L
QUIET=			# -q
RAW=			# -r
ROOTDIR=		# -R rootdir
SERVICE=		# -s svcname
SHOW_ALL=		# -a / -A
SHOW_EQUALS=		# -e
SHOW_FILE=		# -F
SHOW_NAME=1		# -n
SHOW_VALUE=1		# -N
VERBOSE=		# -v

#
# Miscellaneous
#
SEP=": "

############################################################ FUNCTIONS

# warn [$fmt [$opts ...]]
#
# Produce an error message on stderr.
#
warn()
{
	local fmt="$1"
	[ "$fmt" ] || return
	shift 1 # fmt
	f_err "%s: $fmt\n" "$pgm" "$@"
}

# die [$fmt [$opts ...]]
#
# Optionally print a message to stderr before exiting with failure status.
#
die()
{
	warn "$@"
	exit $FAILURE
}

# usage [$fmt [$opts ...]]
#
# Prints a short syntax statement and exits. Optionally preceded by an error.
#
usage()
{
	warn "$@"
	f_err "Usage: %s [OPTIONS] %s\n" "$pgm" \
		"{name[[+|-|.]=value] ... | -a | -A | -l | -L [name ...]}"
	f_err "Try \`%s --help' for more information.\n" "$pgm"
	die
}

# help
#
# Prints a full syntax statement and exits.
#
help()
{
	local optfmt="\t%-11s%s\n"
	local envfmt="\t%-17s%s\n"

	f_err "Usage: %s [OPTIONS] name[[+|-|.]=value] ...\n" "$pgm"
	f_err "Usage: %s [OPTIONS] -a | -A\n" "$pgm"
	f_err "Usage: %s [OPTIONS] -l | -L [name ...]\n" "$pgm"

	f_err "OPTIONS:\n"
	f_err "$optfmt" "-A" \
	      "Dump a list of all configuration variables (incl. defaults)."
	f_err "$optfmt" "-a" \
	      "Dump a list of all non-default configuration variables."
	f_err "$optfmt" "-c" \
	      "Check. Return success if set or no changes, else error."
	f_err "$optfmt" "-D" \
	      "Show default value(s) only (this is the same as setting"
	f_err "$optfmt" "" \
	      "RC_CONFS to NULL or passing \`-f' with a NULL file-argument)."
	f_err "$optfmt" "-d" \
	      "Print a description of the given variable."
	f_err "$optfmt" "-E" \
	      "Existing files only with \`-[lL]' or when changing a setting."
	f_err "$optfmt" "-e" \
	      "Print query results as \`var=value' (useful for producing"
	f_err "$optfmt" "" \
	      "output to be fed back in). Ignored if \`-n' is specified."
	f_err "$optfmt" "-F" \
	      "Show only the last rc.conf(5) file each directive is in."
	f_err "$optfmt" "-f file" \
	      "Operate on the specified file(s) instead of rc_conf_files."
	f_err "$optfmt" "" \
	      "Can be specified multiple times for additional files."
	f_err "$optfmt" "-h" \
	      "Print a short usage statement to stderr and exit."
	f_err "$optfmt" "--help" \
	      "Print this message to stderr and exit."
	f_err "$optfmt" "-i" \
	      "Ignore unknown variables."
	f_err "$optfmt" "-j jail" \
	      "The jid or name of the jail to operate within."
	f_err "$optfmt" "-L" \
	      "List all configuration files including rc.conf.d entries."
	f_err "$optfmt" "-l" \
	      "List configuration files used at startup on stdout and exit."
	f_err "$optfmt" "-N" \
	      "Show only variable names, not their values."
	f_err "$optfmt" "-n" \
	      "Show only variable values, not their names."
	f_err "$optfmt" "-q" \
	      "Quiet. Disable verbose and hide certain errors."
	f_err "$optfmt" "-R dir" \
	      "Operate within the root directory \`dir' rather than \`/'."
	f_err "$optfmt" "-r" \
	      "Show raw, unexpanded value(s)."
	f_err "$optfmt" "-s name" \
	      "Process additional \`rc.conf.d' entries for service name."
	f_err "$optfmt" "" \
	      "Ignored if \`-f file' is given."
	f_err "$optfmt" "-v" \
	      "Verbose. Print the pathname of the specific rc.conf(5)"
	f_err "$optfmt" "" \
	      "file where the directive was found."
	f_err "$optfmt" "--version" \
	      "Print version information to stdout and exit."
	f_err "$optfmt" "-x" \
	      "Remove variable(s) from specified file(s)."
	f_err "\n"

	f_err "ENVIRONMENT:\n"
	f_err "$envfmt" "RC_CONFS" \
	      "Override default rc_conf_files (even if set to NULL)."
	f_err "$envfmt" "RC_DEFAULTS" \
	      "Location of \`/etc/defaults/rc.conf' file."

	die
}

# jail_depend
#
# Dump dependencies such as include files to stdout to be piped-into sh(1)
# running via jexec(8)/chroot(8). As a security measure, this prevents existing
# library files from being loaded in the jail. This also relaxes the
# requirement to have these files in every jail before sysrc can be used on
# said jail.
#
jail_depend()
{
	#
	# Print include dependencies
	#
	cat $SYSRC_SHARE/sysrc.subr
}

# escape_required $string
#
# Returns success if $string contains characters unsafe if not escaped. These
# are characters that would alter the contents or break a shell interpreter's
# parsing if simply double-quoted.
#
escape_required()
{
	case "$1" in
	*[\'\"\$\`\\]*) return $SUCCESS ;;
	esac
	return $FAILURE
}

# quote_required $string
#
# Returns success if $string contains characters unsafe if left unquoted.
#
quote_required()
{
	case "$1" in
	*[!-%+,./0-9:=@A-Z\]\[_a-z{}]*) return $SUCCESS ;;
	esac
	return $FAILURE
}

# shell_fmt $fmt $string
#
# $fmt should contain precisely one %s. Depending on the contents of $string,
# Replace %s in $fmt either with "$string", '$string', or $string.
#
shell_fmt()
{
	local fmt="$1"
	local string="$2"

	if escape_required "$string"; then
		f_shell_escape "$string" string
		printf "$fmt" "'$string'"
	elif quote_required "$string"; then
		printf "$fmt" "\"$string\""
	else
		printf "$fmt" "$string"
	fi
}

############################################################ MAIN SOURCE

#
# Perform sanity checks
#
[ $# -gt 0 ] || usage "no names provided" # NOTREACHED

#
# Check for `--help' and `--version' command-line option
#
for arg in "$@"; do
	case "$arg" in
	--) break ;;
	--help) help ;; # NOTREACHED
	--version) # see GLOBALS
		echo "$SYSRC_VERSION"
		exit $FAILURE ;;
	esac
done
unset arg

#
# Process command-line flags
#
while getopts AacDdEeFf:hij:LlNnqR:rs:vXx flag; do
	case "$flag" in
	A) SHOW_ALL=2 ;;
	a) SHOW_ALL=${SHOW_ALL:-1} ;;
	c) CHECK_ONLY=1 ;;
	D) DEFAULT=1 RC_CONFS= ;;
	d) DESCRIBE=1 ;;
	E) EXISTING_ONLY=1 ;;
	e) SHOW_EQUALS=1 ;;
	F) SHOW_FILE=1 ;;
	f) DEFAULT= RC_CONFS="$RC_CONFS${RC_CONFS:+ }$OPTARG" ;;
	h) usage ;; # NOTREACHED
	i) IGNORE_UNKNOWNS=1 ;;
	j) [ "$OPTARG" ] ||
		die "Missing or null argument to \`-j' flag"
	   JAIL="$OPTARG" ;;
	L) LIST_SERVICE_CONFS=1 ;;
	l) LIST_CONFS=1 ;;
	N) SHOW_VALUE= ;;
	n) SHOW_NAME= ;;
	q) QUIET=1 VERBOSE= ;;
	R) [ "$OPTARG" ] ||
		die "Missing or null argument to \`-R' flag"
	   ROOTDIR="$OPTARG" ;;
	r) RAW=1 ;;
	s) [ "$OPTARG" ] ||
		die "Missing or null argument to \`-s' flag"
	   SERVICE="$OPTARG" ;;
	v) VERBOSE=1 QUIET= ;;
	X) DELETE=2 ;;
	x) DELETE=${DELETE:-1} ;;
	\?) usage ;; # NOTREACHED
	esac
done
shift $(( $OPTIND - 1 ))

#
# Sanity checks
#
if [ "$SHOW_ALL" ]; then
	[ $# -eq 0 ] || usage "-a/-A do not take names" # NOTREACHED
fi
if [ "$DESCRIBE" ]; then
	if [ "$CHECK_ONLY$DELETE$LIST_CONFS$LIST_SERVICE_CONFS$RAW" ]; then
		if [ "$DELETE" = "2" ]; then
			# NB: Do not advertise secret `-X' unless it was used
			usage "-d cannot be combined with -c/-l/-L/-r/-x/-X"
			# NOTREACHED
		fi
		usage "-d cannot be combined with -c/-l/-L/-r/-x" # NOTREACHED
	fi
	for item in "$@"; do
		case "$item" in
		*=*) usage "-d does not take values" ;; # NOTREACHED
		esac
	done
	unset item
fi
[ "$JAIL" -a "$ROOTDIR" ] &&
	usage "-j and -R are mutually exclusive" # NOTREACHED

#
# Process `-L' flag
#
if [ "$LIST_SERVICE_CONFS" ]; then
	list=

	#
	# List rc_conf_files if no service names given
	#
	files=
	[ $# -eq 0 ] && files=$( f_sysrc_get rc_conf_files )
	set -f # noglob
	for file in $files; do
		if [ "$EXISTING_ONLY" ]; then
			[ -e "$file" -a ! -d "$file" ] || continue
		fi
		case "$list" in
		*" $file "*|*" $file") continue ;;
		esac
		list="$list $file"
		[ "$VERBOSE$SHOW_EQUALS" ] || echo "$file"
	done
	set +f # glob
	list="${list# }"
	if [ $# -eq 0 ]; then
		if [ "$VERBOSE" ]; then
			echo "rc_conf_files$SEP$list"
		elif [ "$SHOW_EQUALS" ]; then
			shell_fmt "rc_conf_files=%s\n" "$list"
		fi
	fi

	#
	# List rc.conf.d entries
	#
	retval=$SUCCESS
	for service in ${*:-$( service -l )}; do
		slist=
		f_sysrc_service_configs $service files || retval=$? continue
		set -f # noglob
		for file in $files; do
			if [ "$EXISTING_ONLY" ]; then
				[ -e "$file" -a ! -d "$file" ] || continue
			fi
			if [ ! "$VERBOSE" -a ! "$SHOW_EQUALS" ]; then
				case "$list" in
				*" $file "*|*" $file") continue ;;
				esac
			fi
			slist="$slist $file"
		done
		set +f # glob
		slist="${slist# }"
		if [ $# -gt 0 ]; then
			[ "$slist" ] || retval=$?
		fi
		if [ "$VERBOSE" ]; then
			[ "$slist" ] && echo "$service$SEP$slist"
			continue
		elif [ "$SHOW_EQUALS" ]; then
			[ "$slist" ] && shell_fmt "$service=%s\n" "$slist"
			continue
		elif [ $# -eq 0 -o ! "$QUIET" ]; then
			set -f # noglob
			for item in $slist; do
				echo "$item"
			done
			set +f # glob
		fi
		list="$list${slist:+ }$slist"
	done

	exit $retval
fi

#
# Validate arguments
#
for name in "$@"; do
	# NB: shell expansion syntax removed first
	name="${name%%:[+=-]*}"
	name="${name%%.=*}" # string append
	name="${name%%[%#+=-]*}"
	[ "$name" = "${name#*[!$VALID_VARNAME_CHARS]}" ] ||
		die "%s: name contains characters not allowed in shell" "$name"
done
unset name

#
# Process `-s name' argument
#
if [ "$SERVICE" -a ! "${RC_CONFS+set}" ]; then
	if f_sysrc_service_configs "$SERVICE" RC_CONFS; then
		rc_conf_files=$( f_sysrc_get rc_conf_files )
		RC_CONFS="$rc_conf_files${RC_CONFS:+ }$RC_CONFS"
		unset rc_conf_files
	else
		unset RC_CONFS
	fi
fi

#
# Process `-E' option flag
#
if [ "$EXISTING_ONLY" ]; then
	#
	# To get f_sysrc_*() to ignore missing rc_conf_files, we have to use
	# RC_CONFS to override the unpreened value. If RC_CONFS already has a
	# value (`-D', `-f file', `-s name', or inherited from parent), use it.
	# Otherwise, include filtered contents of rc_conf_files.
	#
	RC_CONFS=$(
		if [ "${RC_CONFS+set}" ]; then
			set -- $RC_CONFS
		else
			set -- $( f_sysrc_get rc_conf_files )
		fi
		while [ $# -gt 0 ]; do
			[ -f "$1" ] && echo -n " $1"
			shift
		done
	)
	RC_CONFS="${RC_CONFS# }"
fi

#
# Process `-l' option flag
#
if [ "$LIST_CONFS" ]; then
	[ $# -eq 0 ] || usage "-l does not take names" # NOTREACHED
	if [ "$DEFAULT" ]; then
		list="$RC_DEFAULTS"
	elif [ "${RC_CONFS+set}" ]; then
		list="$RC_CONFS"
	else
		list=$( f_sysrc_get rc_conf_files )
	fi
	set -f # noglob
	for item in $list; do
		echo "$item"
	done
	set +f # glob
	exit $SUCCESS
fi

#
# [More] Sanity checks (e.g., "sysrc --")
#
[ $# -eq 0 -a ! "$SHOW_ALL" ] && usage "no names provided" # NOTREACHED

#
# Taint-check all rc.conf(5) files
#
errmsg="Exiting due to previous syntax errors"
if [ "${RC_CONFS+set}" ]; then
	( set -f # noglob
	  for i in $RC_CONFS; do
	  	[ -e "$i" ] || continue
	  	/bin/sh -n "$i" || exit $FAILURE
	  done
	  exit $SUCCESS
	) || die "$errmsg"
else
	/bin/sh -n "$RC_DEFAULTS" || die "$errmsg"
	( . "$RC_DEFAULTS"
	  set -f # noglob
	  for i in $rc_conf_files; do
	  	[ -e "$i" ] || continue
	  	/bin/sh -n "$i" || exit $FAILURE
	  done
	  exit $SUCCESS
	) || die "$errmsg"
fi

#
# Process `-x' (and secret `-X') command-line options
#
errmsg="\`-x' option incompatible with \`-a'/\`-A' options"
errmsg="$errmsg (use \`-X' to override)"
if [ "$DELETE" -a "$SHOW_ALL" ]; then
	[ "$DELETE" = "2" ] || die "$errmsg"
elif [ "$DELETE" = "2" ]; then
	die "-X requires -a/-A" # NOTREACHED
elif [ "$DELETE" ]; then
	for item in "$@"; do
		case "$item" in
		*=*) die "%s: -x does not take a value" "$item" ;;
		esac
	done
	unset item
fi

#
# Pre-flight for `-c' command-line option
#
[ "$CHECK_ONLY" -a "$SHOW_ALL" ] &&
	die "\`-c' option incompatible with \`-a'/\`-A' options"

#
# Process `-e', `-N', and `-n' command-line options
#
[ "$SHOW_FILE" ] && SHOW_EQUALS=
[ "$SHOW_NAME" ] || SHOW_EQUALS=
[ "$VERBOSE" = "0" ] && VERBOSE=
if [ ! "$SHOW_VALUE" ]; then
	SHOW_NAME=1
	SHOW_EQUALS=
fi

#
# Process `-j jail' and `-R dir' command-line options
#
if [ "$JAIL" -o "$ROOTDIR" ]; then
	#
	# Reconstruct the arguments that we want to carry-over
	# NB: Order matters
	#
	args="
		${VERBOSE:+-v}
		${QUIET:+-q}
		${RAW:+-r}
		$( [ "$DELETE" = "1" ] && echo \ -x )
		$( [ "$DELETE" = "2" ] && echo \ -X )
		$( [ "$SHOW_ALL" = "1" ] && echo \ -a )
		$( [ "$SHOW_ALL" = "2" ] && echo \ -A )
		${CHECK_ONLY:+-c}
		${DEFAULT:+-D}
		${EXISTING_ONLY:+-E}
		${LIST_CONFS:+-l}
		${LIST_SERVICE_CONFS:+-L}
		${DESCRIBE:+-d}
		${SHOW_EQUALS:+-e}
		${IGNORE_UNKNOWNS:+-i}
		$( [ "$SHOW_NAME"  ] || echo \ -n )
		$( [ "$SHOW_VALUE" ] || echo \ -N )
		$( [ "$SHOW_FILE"  ] && echo \ -F )
	"
	if [ "$SERVICE" ]; then
		f_shell_escape "$SERVICE" _SERVICE
		args="$args -s '$_SERVICE'"
		unset _SERVICE
	fi
	if [ "${RC_CONFS+set}" ]; then
		f_shell_escape "$RC_CONFS" _RC_CONFS
		args="$args -f '$_RC_CONFS'"
		unset _RC_CONFS
	fi
	for arg in "$@"; do
		f_shell_escape "$arg" arg
		args="$args '$arg'"
	done
	unset arg

	#
	# If both are supplied, `-j jail' supercedes `-R dir'
	#
	if [ "$JAIL" ]; then
		#
		# Re-execute ourselves with sh(1) via jexec(8)
		#
		( echo set -- $args
		  jail_depend
		  cat $0
		) | env - RC_DEFAULTS="$RC_DEFAULTS" \
		    	/usr/sbin/jexec "$JAIL" /bin/sh
		exit $?
	elif [ "$ROOTDIR" ]; then
		#
		# Make sure that the root directory specified is not to any
		# running jails.
		#
		# NOTE: To maintain backward compatibility with older jails on
		# older systems, we will not perform this check if either the
		# jls(1) or jexec(8) utilities are missing.
		#
		if f_have jexec && f_have jls; then
			jid=$( jls jid path |
				while read JID JROOT; do
					[ "$JROOT" = "$ROOTDIR" ] || continue
					echo $JID
				done
			)

			#
			# If multiple running jails match the specified root
			# directory, exit with error.
			#
			if [ "$jid" -a "${jid%[$IFS]*}" != "$jid" ]; then
				die "%s: %s" "$ROOTDIR" \
				    "$( echo "Multiple jails claim this" \
				             "directory as their root." \
				             "(use \`-j jail' instead)" )"
			fi

			#
			# If only a single running jail matches the specified
			# root directory, implicitly use `-j jail'.
			#
			if [ "$jid" ]; then
				#
				# Re-execute outselves with sh(1) via jexec(8)
				#
				( echo set -- $args
				  jail_depend
				  cat $0
				) | env - RC_DEFAULTS="$RC_DEFAULTS" \
					/usr/sbin/jexec "$jid" /bin/sh
				exit $?
			fi

			# Otherwise, fall through and allow chroot(8)
		fi

		#
		# Re-execute ourselves with sh(1) via chroot(8)
		#
		( echo set -- $args
		  jail_depend
		  cat $0
		) | env - RC_DEFAULTS="$RC_DEFAULTS" \
		    	/usr/sbin/chroot "$ROOTDIR" /bin/sh
		exit $?
	fi
fi

#
# Process `-a' or `-A' command-line options
#
if [ "$SHOW_ALL" ]; then
	#
	# Get a list of variables that are currently set in the rc.conf(5)
	# files (including `/etc/defaults/rc.conf') by performing a call to
	# source_rc_confs() in a clean environment.
	#
	( # Operate in a sub-shell to protect the parent environment
		#
		# Set which variables we want to preserve in the environment.
		# Append the pipe-character (|) to the list of internal field
		# separation (IFS) characters, allowing us to use the below
		# list both as an extended grep (-E) pattern and argument list
		# (required to first get f_clean_env() to preserve these in the
		# environment and then later to prune them from the list of
		# variables produced by set(1)).
		#
		IFS="$IFS|"
		EXCEPT="IFS|EXCEPT|PATH|RC_DEFAULTS|OPTIND|DESCRIBE|SEP"
		EXCEPT="$EXCEPT|DELETE|SHOW_ALL|SHOW_EQUALS|SHOW_NAME|DEFAULT"
		EXCEPT="$EXCEPT|SHOW_VALUE|SHOW_FILE|VERBOSE|RC_CONFS|SERVICE"
		EXCEPT="$EXCEPT|pgm|SUCCESS|FAILURE|CHECK_ONLY|EXISTING_ONLY"
		EXCEPT="$EXCEPT|LIST_CONFS|LIST_SERVICE_CONFS|RAW"
		EXCEPT="$EXCEPT|f_sysrc_desc_awk|f_sysrc_delete_awk"
		EXCEPT="$EXCEPT|f_sysrc_get_raw_awk"

		#
		# Clean the environment (except for our required variables)
		# and then source the required files.
		#
		f_clean_env --except $EXCEPT
		if [ -f "$RC_DEFAULTS" -a -r "$RC_DEFAULTS" ]; then
			. "$RC_DEFAULTS"

			#
			# If passed `-a' (rather than `-A'), re-purge the
			# environment, removing the rc.conf(5) defaults.
			#
			[ "$SHOW_ALL" = "1" ] &&
				f_clean_env --except rc_conf_files $EXCEPT

			#
			# If `-f file' was passed, set $rc_conf_files to an
			# explicit value, modifying the default behavior of
			# source_rc_confs().
			#
			if [ "${RC_CONFS+set}" ]; then
				[ "$SHOW_ALL" = "1" -a "$SERVICE" -a \
					! "$DEFAULT" ] || rc_conf_files=
				rc_conf_files="$rc_conf_files $RC_CONFS"
				rc_conf_files="${rc_conf_files# }"
				rc_conf_files="${rc_conf_files% }"
			fi

			set -f # noglob
			source_rc_confs
			set +f # glob

			#
			# If passed `-a' (rather than `-A'), remove
			# `rc_conf_files' unless it was defined somewhere
			# other than rc.conf(5) defaults.
			#
			[ "$SHOW_ALL" = "1" -a \
			  "$( f_sysrc_find rc_conf_files )" = "$RC_DEFAULTS" \
			] && unset rc_conf_files
		fi

		for NAME in $( set |
			awk -F= '/^[[:alpha:]_][[:alnum:]_]*=/ {print $1}' |
			grep -Ev "^($EXCEPT)$"
		); do
			#
			# If `-d' is passed, describe rather than expand value
			#
			if [ "$DESCRIBE" ]; then
				if [ ! "$SHOW_NAME" ]; then
					echo "$( f_sysrc_desc "$NAME" )"
				elif [ ! "$SHOW_VALUE" ]; then
					echo "$NAME"
				elif [ "$SHOW_EQUALS" ]; then
					desc=$( f_sysrc_desc "$NAME" )
					shell_fmt "$NAME=%s\n" "$desc"
				else
					echo "$NAME$SEP$(
						f_sysrc_desc "$NAME"
					)"
				fi
				continue
			fi

			#
			# If `-F' is passed, find it and move on
			#
			if [ "$SHOW_FILE" ]; then
				[ "$SHOW_NAME" ] && echo -n "$NAME$SEP"
				f_sysrc_find "$NAME"
				continue
			fi

			#
			# If `-X' is passed, delete the variables
			#
			if [ "$DELETE" = "2" ]; then
				f_sysrc_delete "$NAME"
				continue
			fi

			if [ "$VERBOSE" ]; then
				if [ "$SHOW_EQUALS" ]; then
					file=$( f_sysrc_find "$NAME" )
					shell_fmt "_file_$NAME=%s " "$file"
				else
					echo -n "$( f_sysrc_find "$NAME" )$SEP"
				fi
			fi

			#
			# If `-N' is passed, simplify the output
			#
			if [ ! "$SHOW_VALUE" ]; then
				echo "$NAME"
				continue
			fi

			value=$( f_sysrc_get${RAW:+_raw} "$NAME" )
			if [ "$SHOW_EQUALS" ]; then
				shell_fmt "$NAME=%s\n" "$value"
			else
				echo "${SHOW_NAME:+$NAME$SEP}$value"
			fi

		done
	)

	#
	# Ignore the remainder of positional arguments.
	#
	exit $SUCCESS
fi

#
# Process command-line arguments
#
status=$SUCCESS
while [ $# -gt 0 ]; do
	NAME="${1%%=*}"

	case "$NAME" in
	*+) mode=LISTAPPEND NAME="${NAME%+}" ;;
	*-) mode=LISTREMOVE NAME="${NAME%-}" ;;
	*.) mode=STRAPPEND NAME="${NAME%.}" ;;
	 *) mode=ASSIGN
	esac

	case "$1" in
	*=*)
		# If verbose, prefix line with where the directive lives
		if [ "$VERBOSE" -a ! "$CHECK_ONLY" ]; then
			file=$( f_sysrc_find "$NAME" )
			[ "$file" = "$RC_DEFAULTS" -o ! "$file" ] &&
				file=$( f_sysrc_get 'rc_conf_files%%[$IFS]*' )
			if [ "$SHOW_EQUALS" ]; then
				shell_fmt "_file_$NAME=%s " "$file"
			else
				echo -n "$file$SEP"
			fi
		fi

		#
		# Determine both `before' value and appropriate `new' value
		#
		case "$mode" in
		LISTAPPEND)
			before=$( f_sysrc_get_raw "$NAME" )
			add="${1#*=}"
			delim="${add%"${add#?}"}" # first character
			oldIFS="$IFS"
			case "$delim" in
			""|[$IFS]|[-a-zA-Z0-9./_*~$]) delim=" " ;;
			*) IFS="$delim"
			esac
			new="$before"
			set -f # noglob
			for a in $add; do
				[ "$a" ] || continue
				skip=
				for b in $before; do
					[ "$b" = "$a" ] && skip=1 break
				done
				[ "$skip" ] || new="$new$delim$a"
			done
			set +f # glob
			new="${new#"$delim"}" IFS="$oldIFS"
			unset add delim oldIFS a skip b
			[ "$SHOW_FILE" ] && before=$( f_sysrc_find "$NAME" )
			;;
		LISTREMOVE)
			before=$( f_sysrc_get_raw "$NAME" )
			remove="${1#*=}"
			delim="${remove%"${remove#?}"}" # first character
			oldIFS="$IFS"
			case "$delim" in
			""|[$IFS]|[-a-zA-Z0-9./_*~$]) delim=" " ;;
			*) IFS="$delim"
			esac
			new=
			set -f # noglob
			for b in $before; do
				[ "$b" ] || continue
				add=1
				for r in $remove; do
					[ "$r" = "$b" ] && add= break
				done
				[ "$add" ] && new="$new$delim$b"
			done
			set +f # glob
			new="${new#"$delim"}" IFS="$oldIFS"
			unset remove delim oldIFS b add r
			[ "$SHOW_FILE" ] && before=$( f_sysrc_find "$NAME" )
			;;
		STRAPPEND)
			before=$( f_sysrc_get_raw "$NAME" )
			add="${1#*=}"
			new="$add"
			[ "$before" ] && new="$before $add"
			unset add
			[ "$SHOW_FILE" ] && before=$( f_sysrc_find "$NAME" )
			;;
		*) # ASSIGN
			if [ "$SHOW_FILE" ]; then
				before=$( f_sysrc_find "$NAME" )
			else
				before=$( f_sysrc_get_raw "$NAME" )
			fi
			new="${1#*=}"
		esac

		#
		# If `-c' is passed, simply compare and move on
		# NB: `-e' ignored when given `-c'
		#
		if [ "$CHECK_ONLY" ]; then
			if ! IGNORED=$( f_sysrc_get "$NAME?" ); then
				status=$FAILURE
				[ "$QUIET" ] ||
					warn "%s: not currently set" "$NAME"
			elif [ "$new" != "$before" ]; then
				status=$FAILURE
				if [ "$VERBOSE" ]; then
					warn "%s: %s: would change %s" \
						"$( f_sysrc_find "$NAME" )" \
						"$NAME" \
						"from \`$before' to \`$new'"
				elif [ ! "$QUIET" ]; then
					warn "%s: value differs" "$NAME"
				fi
			elif [ "$VERBOSE" ]; then
				warn "%s: %s: already set to \`%s'" \
					"$( f_sysrc_find "$NAME" )" \
					"$NAME" "$before"
			fi
			shift 1
			continue
		fi

		# Empty append or remove changes nothing
		case "$mode:${1#*=}" in
		LISTAPPEND:|LISTREMOVE:|STRAPPEND:)
			if [ "$QUIET" ]; then
				: nothing
			elif [ "$SHOW_EQUALS" ]; then
				shell_fmt "$NAME=%s # unchanged\n" "$before"
			elif [ ! "$SHOW_VALUE" ]; then
				echo "$NAME (unchanged)"
			else
				echo "${SHOW_NAME:+$NAME$SEP}$before" \
					"(unchanged)"
			fi
			shift 1
			continue ;;
		esac

		# An unset name is not already NULL
		if [ "$before" = "$new" ] &&
		   IGNORED=$( f_sysrc_get "$NAME?" )
		then
			if [ "$QUIET" ]; then
				: nothing
			elif [ "$SHOW_EQUALS" ]; then
				shell_fmt "$NAME=%s # unchanged\n" "$before"
			elif [ ! "$SHOW_VALUE" ]; then
				echo "$NAME (unchanged)"
			else
				echo "${SHOW_NAME:+$NAME$SEP}$before" \
					"(unchanged)"
			fi
			shift 1
			continue
		fi

		#
		# If `-N' is passed, simplify the output
		#
		if [ ! "$SHOW_VALUE" ]; then
			if [ ! "$QUIET" ]; then
				echo "$NAME"
			fi
			f_sysrc_set "$NAME" "$new" || status=$FAILURE
		else
			if f_sysrc_set "$NAME" "$new"; then
				if [ ! "$QUIET" ]; then
					if [ "$SHOW_FILE" ]; then
						after=$( f_sysrc_find "$NAME" )
					else
						after=$(
							f_sysrc_get_raw "$NAME"
						)
					fi
					if [ "$SHOW_EQUALS" ]; then
						shell_fmt "_$NAME=%s " "$before"
						shell_fmt "$NAME=%s\n" "$after"
					else
						if [ "$SHOW_NAME" ]; then
							echo -n "$NAME$SEP"
						fi
						echo "$before -> $after"
					fi
				fi
			else
				status=$FAILURE
			fi
		fi
		;;

	*)
		if ! IGNORED=$( f_sysrc_get "$NAME?" ); then
			[ "$IGNORE_UNKNOWNS" -o "$QUIET" ] ||
				warn "unknown variable '%s'" "$NAME"
			shift 1
			status=$FAILURE
			continue
		fi

		# The above check told us what we needed for `-c'
		if [ "$CHECK_ONLY" ]; then
			shift 1
			continue
		fi

		#
		# Like sysctl(8), when `-d' is passed, desribe it
		# rather than expanding it
		#
		if [ "$DESCRIBE" ]; then
			if [ ! "$SHOW_NAME" ]; then
				echo "$( f_sysrc_desc "$NAME" )"
			elif [ ! "$SHOW_VALUE" ]; then
				echo "$NAME"
			elif [ "$SHOW_EQUALS" ]; then
				desc=$( f_sysrc_desc "$NAME" )
				shell_fmt "$NAME=%s\n" "$desc"
			else
				echo "$NAME$SEP$( f_sysrc_desc "$NAME" )"
			fi
			shift 1
			continue
		fi

		#
		# If `-x' or `-X' is passed, delete the variable
		#
		if [ "$DELETE" ]; then
			f_sysrc_delete "$NAME" || status=$FAILURE
			shift 1
			continue
		fi

		#
		# If `-F' is passed, find it and move on
		#
		if [ "$SHOW_FILE" ]; then
			[ "$SHOW_NAME" ] && echo -n "$NAME$SEP"
			f_sysrc_find "$NAME"
			shift 1
			continue
		fi

		if [ "$VERBOSE" ]; then
			if [ "$SHOW_EQUALS" ]; then
				file=$( f_sysrc_find "$NAME" )
				shell_fmt "_file_$NAME=%s " "$file"
			else
				echo -n "$( f_sysrc_find "$NAME" )$SEP"
			fi
		fi

		#
		# If `-N' is passed, simplify the output
		#
		if [ ! "$SHOW_VALUE" ]; then
			echo "$NAME"
		elif [ "$SHOW_EQUALS" ]; then
			value=$( f_sysrc_get${RAW:+_raw} "$NAME" )
			shell_fmt "$NAME=%s\n" "$value"
		else
			echo "${SHOW_NAME:+$NAME$SEP}$(
				f_sysrc_get${RAW:+_raw} "$NAME"
			)"
		fi
	esac
	shift 1
done

exit $status # $SUCCESS unless error occurred with either `-c' or `-x'

################################################################################
# END
################################################################################
