+# Show the help messages.
+do_help()
+{
+ if [ -z "$1" ] ; then
+ # This is currently invoked in all kinds of circumstances,
+ # including when the user made a usage error. Should we end up
+ # providing more than a short help message, then we should
+ # differentiate.
+ # Petr's comment: http://marc.info/?l=git&m=122718711327376&w=2
+
+ ## Build available commands list for help output
+
+ cmds=
+ sep=
+ for cmd in "@cmddir@"/tg-*; do
+ ! [ -r "$cmd" ] && continue
+ # strip directory part and "tg-" prefix
+ cmd="$(basename "$cmd")"
+ cmd="${cmd#tg-}"
+ cmds="$cmds$sep$cmd"
+ sep="|"
+ done
+
+ echo "TopGit v$TG_VERSION - A different patch queue manager"
+ echo "Usage: tg [-r REMOTE] ($cmds|help) ..."
+ elif [ -r "@cmddir@"/tg-$1 ] ; then
+ setup_pager
+ @cmddir@/tg-$1 -h 2>&1 || :
+ echo
+ if [ -r "@sharedir@/tg-$1.txt" ] ; then
+ cat "@sharedir@/tg-$1.txt"
+ fi
+ else
+ echo "`basename $0`: no help for $1" 1>&2
+ do_help
+ exit 1
+ fi
+}
+
+## Pager stuff
+
+# isatty FD
+isatty()
+{
+ test -t $1
+}
+
+# setup_pager
+# Spawn pager process and redirect the rest of our output to it
+setup_pager()
+{
+ isatty 1 || return 0
+
+ # TG_PAGER = GIT_PAGER | PAGER | less
+ # NOTE: GIT_PAGER='' is significant
+ TG_PAGER=${GIT_PAGER-${PAGER-less}}
+
+ [ -z "$TG_PAGER" -o "$TG_PAGER" = "cat" ] && return 0
+
+
+ # now spawn pager
+ export LESS="${LESS:-FRSX}" # as in pager.c:pager_preexec()
+
+ # setup_pager should be called only once per command
+ pager_fifo="$tg_tmp_dir/pager"
+ mkfifo -m 600 "$pager_fifo"
+
+ "$TG_PAGER" < "$pager_fifo" &
+ exec > "$pager_fifo" # dup2(pager_fifo.in, 1)
+
+ # this is needed so e.g. `git diff` will still colorize it's output if
+ # requested in ~/.gitconfig with color.diff=auto
+ export GIT_PAGER_IN_USE=1
+
+ # atexit(close(1); wait pager)
+ # deliberately overwrites the global EXIT trap
+ trap "exec >&-; rm -rf \"$tg_tmp_dir\"; wait" EXIT
+}
+
+# get_temp NAME [-d]
+# creates a new temporary file (or directory with -d) in the global
+# temporary directory $tg_tmp_dir with pattern prefix NAME
+get_temp()
+{
+ mktemp ${2-} "$tg_tmp_dir/$1.XXXXXX"
+}
+
+## Startup
+
+[ -d "@cmddir@" ] ||
+ die "No command directory: '@cmddir@'"
+
+ensure_git_repo_or_die