#!/usr/bin/env bash
#
# Show help for Cogito commands.
# Copyright (c) Petr Baudis, 2005
#
# Takes an optional argument describing the command to show the help for.
# The command can be specified either as 'COMMAND' or 'cg-COMMAND'.
# If the argument is left out an overview of all the Cogito commands will
# be shown.
#
# Note help for a command is also available by passing `--help` or `-h`
# to the command.
#
# OPTIONS
# -------
# -c::
#	Colorize the output.

USAGE="cg-help [-c] [cg-COMMAND | COMMAND]"
_git_repo_unneeded=1

. ${COGITO_LIB:-/usr/lib/cogito/}cg-Xlib

setup_colors()
{
	local color_none="$(tput op)"
	local emphasize="$(tput setaf 1)"
	local desclist="$(tput setaf 3)"
	local cgcmd="$(tput setaf 2)"
	local codesnippet="$(tput setaf 6)"
	local usage="$(tput setaf 3)"
	local section="$(tput setaf 5)"
	local copyright="$(tput setaf 4)"

	apply_colors="
	s/^\(.*\)::/$desclist\1$color_none:/
	s/\`\(cg-[a-z-]*\)\`/$cgcmd\1$color_none/g
	s/\`\([^\`]*\)\`/$codesnippet&$color_none/g
	s/[^A-Z0-9a-z_-]\$ .*/$codesnippet&$color_none/g
	s/'\([^ ]*\)'/$emphasize&$color_none/g
	s/'\(-[A-Z0-9a-z_-]* [^']*\)'/$emphasize&$color_none/g
	s/^Usage: .*/$usage&$color_none/
	/^[A-Z -_]*/,/^---*$/s/^[A-Z -_]*\$/$section&$color_none/
	s/^Copyright .*/$copyright&$color_none/
	"
}

print_command_listing()
{
	for command in "$@"; do
		[ -f "$command" -a ! -L "$command" ] || continue
		cmdname=$(basename $command)

		usage=$(sed -n '/^USAGE=/,0s/.*"\(cg-.*\)"/\1/p' < $command)
		# Some minimal sanity check that we didn't pick up some
		# random binary named cg-*
		[ "$usage" ] || continue
		usage=$(echo "$usage" | sed 's/^cg-[^ ]*//')
		printf "	%-17s %s\n" "$cmdname" "$usage"
	done
}


apply_colors=
while optparse; do
	if optparse -c; then
		setup_colors
	else
		optfail
	fi
done

colorize() {
	sed -e "$apply_colors" | pager
}

if [ "$ARGS" ]; then
	cmd=$(echo "${ARGS[0]}" | sed 's/^cg-//')
	print_help $cmd | colorize
	[ "${PIPESTATUS[0]}" -eq 0 ] && exit
	echo "cg-help: no help available for command \"${ARGS[0]}\""
	echo "Call cg-help without any arguments for the list of available commands"
	exit 1
fi

bin_path="$(dirname $0)"

REGULAR_COMMANDS="$(ls $bin_path/cg-* | grep -v cg-admin- | grep -v cg-X)"
ADVANCED_COMMANDS="$(ls $bin_path/cg-admin-*)"

colorize <<__END__
The Cogito version control system  $(cg-version)

Available commands:
$(print_command_listing $REGULAR_COMMANDS)

Advanced (low-level or dangerous) commands:
$(print_command_listing $ADVANCED_COMMANDS)

These expressions can be used interchangably as "ID"s:
	empty string, "this" or "HEAD" (current HEAD)
	branch name (as registered with cg-branch-add)
	tag name (as registered with cg-tag)
	date string (as recognized by the date tool)
	shortcut hash (shorted unambiguous hash lead)
	commit object hash (as returned by commit-id)
	tree object hash (accepted only by some commands)

For details on individual commands, do e.g.:
	cg-help cg-log
	cg-log --help
(both variants are equivalent)
__END__
