#!/bin/sh -efu

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

# Quote argument for sed basic regular expression and store result into variable.
# Usage example:
# quote_sed_regexp_variable var_pattern "$pattern"
# quote_sed_regexp_variable var_replace "$replace"
# sed "s/$var_pattern/$var_replace/"
quote_sed_regexp_variable() {
	local __quote_set_regexp_variable_var __quote_set_regexp_variable_out
	__quote_set_regexp_variable_var="$1"; shift
	__quote_set_regexp_variable_out="$*"
	if [ -z "${__quote_set_regexp_variable_out##*[\[\].*&^\$\\\\/]*}" ]; then
		__quote_set_regexp_variable_out="$(printf %s "$__quote_set_regexp_variable_out" |
				sed -e 's/[].*&^$[\/]/\\&/g')" ||
			return 1
	fi
	eval "$__quote_set_regexp_variable_var=\"\$__quote_set_regexp_variable_out\""
}

# Quote given arguments for sed basic regular expression.
# Usage example: sed "s/$(quote_sed_regexp "$var_pattern")/$(quote_sed_regexp "$var_replacement")/"
quote_sed_regexp() {
	local result
	quote_sed_regexp_variable result "$@"
	printf %s "$result"
}

# Quote argument for shell and store result into variable.
# Usage example:
# quote_shell_variable var_name "$var_value"
# printf '%s\n' "$var_name"
quote_shell_variable() {
	local __quote_shell_variable_var __quote_shell_variable_out
	__quote_shell_variable_var="$1"; shift
	__quote_shell_variable_out="$*"
	if [ -z "${__quote_shell_variable_out##*[\"\$\`\\\\]*}" ]; then
		__quote_shell_variable_out="$(printf %s "$__quote_shell_variable_out" |
				sed -e 's/[\"$\`\\]/\\&/g')" ||
			return 1
	fi
	eval "$__quote_shell_variable_var=\"\$__quote_shell_variable_out\""
}

# Quote argument for shell.
# Usage example: eval "$var_name=\"$(quote_shell "$var_value")\""
quote_shell() {
	local result
	quote_shell_variable result "$@"
	printf %s "$result"
}

# Remove quote symbol from string
# Usage example: for i in "\"str1\"" "'str2'" "\"str3'"; do echo "$(string_quote_remove "$i")"; done
# str1
# str2
# "str3'
string_quote_remove() {
	local out="$1"
	if [ -z "${1##*'}${1%%'*}" ]; then
		out="${1#'}"
		out="${out%'}"
	elif [ -z "${1##*\"}${1%%\"*}" ]; then
		out="${1#\"}"
		out="${out%\"}"
	fi
	printf %s "$out"
}

fi #__included_shell_quote
