#!/bin/sh
#################################################################
#
#	@(#) tbm -- tmux buffer manager  (c) Apr 2021 hoz HZNET
#
#	* load files into named tmux buffer
#	* -s	show buffer content
#	* -c	clear buffer
#	* -r	rename buffer
#	* -l	list all tmux buffers
#
#	2023-07
#
#	* Option -p to write the whole content of the current pane
#	  to stdout.
#	* Option -d to write a "screen dump" to stdout
#	* Both options allows the tmux "capture-pane" options
#	  (-e -E -N -C) additionally
#
#	Bugs
#		The namespace for files and buffers are different.
#		The filename should be "tainted" before we use
#		it as a buffer name.
#
#################################################################
PATH=/bin:/usr/bin:/usr/local/bin

prog=`basename $0`

usage()
{
	test "$1" && echo "$prog: $1"

	echo "$prog: tmux buffer manager" 1>&2
	echo "usage: $prog -h 			this help" 1>&2
	echo "usage: $prog [<file>]		load file or stdin into the default buffer" 1>&2
	echo "usage: $prog <buffer> <file>	load file into buffer (use '-' for stdin)" 1>&2
	echo "usage: $prog -s [<buffer>]	show (default) buffer content" 1>&2
	echo "usage: $prog -c [<buffer>]	clear (default) buffer" 1>&2
	echo "usage: $prog -r [<buffer>] <name>	rename (default) buffer" 1>&2
	echo "usage: $prog -l			list all buffers" 1>&2
	echo "" 1>&2
	echo "usage: $prog -p [{-e|-N|-J}]	print the content of the current pane to stdout" 1>&2
	echo "usage: $prog -d [{-e|-N}] [-t <pane>]	print a \"screen dump\" of the current pane to stdout" 1>&2

	exit 1
}

act=load
while test $# -gt 0
do
	case $1 in
	-h)	usage ;;
	-l)	act=list ;;
	-s)	act=show ;;
	-c)	act=clear ;;
	-r)	act=rename ;;
	-p|-d)	case "$1" in
		-p)	act=print;;	# print current pane
		-d)	act=dump;;	# screen dump current pane
		esac
		shift
		opts="$@"
		shift $#
		break
		;;
	-*)	usage "Illegal option $1" ;;
	*)	break ;;
	esac
	shift
done

if test $# -ge 1
then
	# "load" with 2 args or all other actions
	if test $act != load -o $# -eq 2
	then
		buffer="$1"
		bufferopt="-b $buffer"
		shift
	else	# "load" with just one arg
		bufferopt="-b $1"
	fi
fi

case $act in
list)	tmux list-buffers
	;;
show)	tmux show-buffer $bufferopt
	;;
clear)	tmux delete-buffer $bufferopt
	;;
load)	tmux load-buffer $bufferopt ${1:-"-"}
	;;
rename)	if test $# -lt 1
	then
		newname="$buffer"
		bufferopt=""
	else
		newname="$1"
	fi
	tmux set-buffer $bufferopt  -n $newname
	;;
print)	tmux capture-pane -pS - $opts
	;;
dump)	tmux capture-pane -J -p $opts
	;;
esac
