#!/bin/sh -efu

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

# quote argument for sed regexp.
quote_sed_regexp() {
	local out="$*"
	if [ -z "${out##*[\[\].^\$\\/]*}" ]; then
		out="$(printf %s "$out" |sed -e 's/[].^$[\/]/\\&/g')" ||
			return 1
	fi
	printf %s "$out"
}

unquote_sed_regexp() {
	local out="$*"
	if [ -z "${out##*\\[\[\].^\$\\/]*}" ]; then
		out="$(printf %s "$out" |sed -e 's/\\\([].^$[\/]\)/\1/g')" ||
			return 1
	fi
	printf %s "$out"
}

# quote argument for shell.
quote_shell() {
	local out="$*"
	if [ -z "${out##*[\"\$\`\\\\]*}" ]; then
		out="$(printf %s "$out" |sed -e 's/["$`\\]/\\&/g')" ||
			return 1
	fi
	printf %s "$out"
}

unquote_shell() {
	local out="$*"
	if [ -z "${out##*\\[\"\$\`\\\\]*}" ]; then
		out="$(printf %s "$out" |sed -e 's/\\\(["$`\\]\)/\1/g')" ||
			return 1
	fi
	printf %s "$out"
}

if [ -n "${__libshell_experimental:-}" ]; then
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

fi
