#!/bin/sh
#
# receive via stdin (from st, tmux) the console output,
# prompt for a recent command and copy the results,

[ -n "${DISPLAY}" ] && menuapp="dmenu" || menuapp="slmenu"
tmpfile=$(mktemp --tmpdir st-cmd-output.XXXXXX)
trap 'rm "$tmpfile"' 0 1 15
sed -n "w ${tmpfile}"
#ps1="(.*)\s[~/].*\\$\s" # The regex representing the ps1 command line prompt
ps1=".*[~/].*\\$\s" # The regex representing the ps1 command line prompt
chosen="$(grep "${ps1}" "${tmpfile}" | sed '$ d' | tac | ${menuapp} -p "Copy which command's output?" -i -l 10 | sed 's/[^^]/[&]/g; s/\^/\\^/g')"
out=$(awk "/^${chosen}$/{p=1;print;next} p&&/^${ps1}/{p=0};p" "${tmpfile}")
if [ -n "${DISPLAY}" ]; then
  printf '%b\n' "${out}" | xclip -selection clipboard
else
  tmux set-buffer "${out}"
fi
