#!/bin/zsh
setopt no_unset warn_create_global
zmodload zsh/stat zsh/datetime || exit $?
typeset -ga clipboards
typeset -g map=/run/display-container-map
#set -x

get-clip() {
	local sel out name=$1
	local -a env=( env )
	[[ -f /run/Xauthority.${DISPLAY#:} ]] && \
		env+=( XAUTHORITY=/run/Xauthority.${DISPLAY#:} )
	for sel in CLIPBOARD PRIMARY; do
		out=$( $env xclip -o -sel $sel ) && \
			[[ -n $out ]] &&
			clipboards[${sel:l}@$name]=$out
	done
}

scan() {
	local d f mtime
	local -a found files stat
	for d in /run/xclipring/*/*(/); do
		local -a l=( $d/*(.Nom) )
		for f in $l[1,2]; do
			zstat -A stat +mtime $f || exit $?
			strftime -s mtime '%Y-%m-%dT%H:%M:%S' $stat[1] || exit $?
			files+=( "$mtime|$f" )
		done
	done
	local -a sorted
	set +s -A sorted $files
	for f in $sorted; do
		mtime=${f%%|*}
		f=${f#*|}
		found=( $map/${f:h:t}=*(N) )
		clipboards+=( $mtime/${${found[1]:-${f:h:t}}##*=}/${f:h:h:t} "$(<$f)" )
	done
}
typeset -f -t scan

print-clip() {
	local name content
	for name content in "${(kv@)clipboards}"; do
		printf '>> %s <<\n%s\n\n' $name $content
	done
}

print-clip-0() {
	local name content
	for name content in "${(kv@)clipboards}"; do
		printf '%s\0' $name $content
	done
}

main() {
	scan
	if (($#)) && [[ $1 == -0 ]]; then
		print-clip-0
	else
		print-clip
	fi
}
main "$@"