#!/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_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"
__shell_var_trim()
{
	unset -f __shell_var_trim
	local r="$1" space=' 	
'
	while [ -n "$r" -a -z "${r##[$space]*[$space]}" ]; do r="${r%?}"; r="${r#?}"; done
	while [ -n "$r" -a -z "${r##*[$space]}" ]; do r="${r%?}"; done
	while [ -n "$r" -a -z "${r%%[$space]*}" ]; do r="${r#?}"; done
	__shell_var_trimo="$r"
}
	local __shell_var_trimo=
	__shell_var_trim "$2"
	eval "$1=\"\$__shell_var_trimo\""
}

### 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
