#!/bin/bash
#  commands - heirarchical command support library

set -e

lib_load 'core/script'


######
# Settings

core_commands_config_init() {
	lib_setting_vars cmd_tempdir
	cmd_tempdir="$user_tempdir/run/$script_name/$$"
}

# error_usage_hook - Use the implementation from this library
error_usage_hook=cmd_error_usage


######
# Functions

cmd_tempfile() { tempfile -d "$cmd_tempdir"; }
cmd_name() {
	local -a a=( "${script[@]}" "$@" )
	( export IFS='_'; echo "${a[*]}"; )
}
cmd_exists() { is_function $(cmd_name "$@"); }

cmd_run() { $(cmd_name) "$@"; }

cmd_dispatch_builtins() {
	local cmd=$1
	local handled=true
	case "$cmd" in
	usage|--usage)
		cmd_usage
		;;
	help|--help|-h|-?)
		cmd_help
		;;
	*)
		handled=false
		;;
	esac
	$handled
}

cmd_dispatch() {
	min_args 1 "$@"
	if cmd_dispatch_builtins "$@"; then
		return
	fi
	local cmd=$1
	if cmd_exists "$cmd"; then
		local script=( "${script[@]}" "$cmd" )
		shift
		cmd_run "$@"
	else
		error_usage "'$cmd' is not a known command"
	fi
}

cmd_exec() {
	min_args 1 "$@"
	local cmd=$1
	shift
	if cmd_exists "$cmd"; then
		$(cmd_name $cmd) "$@"
	fi
}

cmd_exec_something() {
	local cmd=$1
	local -a _script=( "${script[@]}" )
	local -a script=( "${_script[@]}" )
	while [ "${script[*]}" ]; do
		if cmd_exists "$cmd"; then
			cmd_exec "$cmd"
			break
		fi
		list_pop script >/dev/null
	done
}

cmd_usage() {
	local usage
	usage=$(cmd_exec_something usage)
	echo "usage: ${script[*]} $usage"

	if [ "${#script[*]}" -eq 1 -a "$script_name" == "$script" ]; then
		app_usage
	fi

	cat <<USAGE

General Commands:
	usage|--usage			Print basic command usage
	help|--help|-h|-?		Print full command help
USAGE
}

cmd_help() {
	cmd_usage

	local body
	body=$(cmd_exec_something help)
	if [ "$body" ]; then
		echo
		echo "$body"
	fi

	# if present, display support contact name/email
	local support_name="${package_support_name:-contacting this address}"
	if [ "$package_support_email" ]; then
		 cat <<EMAIL

Support for this package is provided by $support_name:
	$package_support_email
EMAIL
	elif [ "$package_support_name" ]; then
		 echo "Support for this package is provided by $support_name."
	fi

	# if present, display package URL
	if [ "$package_url" ]; then
		cat <<URL

For more information, please visit the package webpage:
	$package_url
URL
	fi
}

# error_usage - override stub from 'output' library
cmd_error_usage() {
	! error "$1"
	cmd_usage >&2
	false
}

View the Script Reference Index


Generated on Tue Apr 25 21:20:02 PDT 2017 by mcsh i7 v0.18.0.