#!/bin/sh -efu
### This file is covered by the GNU General Public License,
### which should be included with libshell as the file LICENSE.
### All copyright information are listed in the COPYING.

if [ -z "${__included_shell_var-}" ]; then
__included_shell_var=1

. shell-error

shell_var_is_number()
{
	[ -n "${1##0*}" ] && [ -n "${1##*[!0-9]*}" ] && [ "$1" -gt 0 ] 2>/dev/null ||
		return 1
}

shell_var_is_yes()
{
	[ "$#" -eq 1 ] ||
		fatal "Usage: shell_var_yes value"
	case "$1" in
		[Yy][Ee][Ss]|[Tt][Rr][Uu][Ee]|[Oo][Nn]|[Yy]|1) return 0 ;;
	esac
	return 1
}

shell_var_is_no()
{
	[ "$#" -eq 1 ] ||
		fatal "Usage: shell_var_no value"
	case "$1" in
		[Nn][Oo]|[Ff][Aa][Ll][Ss][Ee]|[Oo][Ff][Ff]|[Nn]|0) return 0 ;;
	esac
	return 1
}

### Strip whitespace from the beginning and end of a string
### Usage: shell_var_trim retval "   aaa bb  aaa "; echo "[$retval]"
### [aaa bb  aaa]
shell_var_trim()
{
	[ "$#" -eq 2 ] ||
		fatal "Usage: shell_var_trim varname value"

	local __shell_var_trimo=

	__shell_var_trim "$2"

	eval "$1=\"\$__shell_var_trimo\""
}

__shell_var_trim()
{
	local r="$1" space=' 	
'
	local lead lead_pat trail trail_pat

	lead_pat="[!$space]*"
	trail_pat="*[!$space]"

	# ${r%%$lead_pat} is the leading whitespace run: the longest suffix
	# which starts with a non-space character is the rest of the string,
	# so the difference is exactly the leading whitespace (empty when the
	# string does not start with one, the whole string when it is all
	# whitespace). Strip it all at once instead of character by character.
	lead="${r%%$lead_pat}"
	r="${r#"$lead"}"

	# Symmetrically, cutting the longest prefix which ends with a
	# non-space character leaves exactly the trailing whitespace run.
	trail="${r##$trail_pat}"
	r="${r%"$trail"}"

	__shell_var_trimo="$r"
}

### Remove quote symbol from string
### Usage example:
### for i in "\"str1\"" "'str2'" "\"str3'"; do
###    shell_var_unquote var "$i";
###    echo "$var";
### done
###
### Result:
### str1
### str2
### "str3'
###
shell_var_unquote()
{
	[ "$#" -eq 2 ] ||
		fatal "Usage: shell_var_unquote varname value"
__shell_var_unquote()
{
	local o="$1"
	if [ -z "${o##*\'}${o%%\'*}" ]; then
		o="${o#\'}" o="${o%\'}"
	elif [ -z "${o##*\"}${o%%\"*}" ]; then
		o="${o#\"}" o="${o%\"}"
	fi
	__shell_var_unquoteo="$o"
}
	local __shell_var_unquoteo
	__shell_var_unquote "$2"
	unset -f __shell_var_unquote
	eval "$1=\"\$__shell_var_unquoteo\""
}

fi #__included_shell_var
