#!/bin/sh
BUFFER_CMD='sh -c '\''
    print_if_nonempty () {
        test -z "$1" || printf "%s\n" "$1"
    }

    declare DISPLAY
    type -f xclip > /dev/null 2>&1 &&
        test -n "$DISPLAY" &&
        {
            OPTIND=1
            while getopts :pscC opt
            do
                case "$opt" in
                p)  print_if_nonempty "$(xclip -o -selection primary)"
                    ;;
                s)  print_if_nonempty "$(xclip -o -selection secondary)"
                    ;;
                c)  print_if_nonempty "$(xclip -o -selection clipboard)"
                    ;;
                C)  : # handled outside
                    ;;
                esac
            done
            shift $(expr $OPTIND - 1)
        }
    test $# -gt 0 && printf "%s\n" "$@"
    cat - > /dev/null'\'' sh "$@"'

mywhich() {
    type -f "$1" >/dev/null 2>&1
}

usage_and_exit () {
    echo "$(basename "$0") [-pscC] [<args>]"
    echo
    echo 'Create a window for temporary storage of text.'
    echo '<args> are printed to the window, if present.'
    echo 'Under X, a new terminal is created, based on $X_TERMINAL_EMULATOR or $XTERM'
    echo 'Arguments:'
    echo '  -C - Set locale to C. (X only).'
    echo '  -p - Paste primary selection into window (X only).'
    echo '  -s - Paste secondary selection into window (X only).'
    echo '  -c - Paste clipboard into window (X only).'
    echo '  -w - Use wide terminal (X only).'
    exit 2
}

geometry="-geometry 80x25"
while getopts :pscChw opt
do
    case "$opt" in
        C) export LC_ALL=C LANG=C
           ;;
    p|s|c) : # handled inside
           ;;
        w) geometry="-geometry 160x25"
           ;;
     h|\?) usage_and_exit
           ;;
    esac
done

declare DISPLAY XTERM X_TERMINAL_EMULATOR
if test -n "$DISPLAY"; then
    if test -n "$XTERM" && mywhich "$XTERM"; then
        xterm="$XTERM"
    elif test -n "$X_TERMINAL_EMULATOR" && mywhich "$X_TERMINAL_EMULATOR"; then
        xterm="$X_TERMINAL_EMULATOR"
    elif mywhich urxvt; then
        xterm=urxvt
    elif mywhich xterm; then
        xterm=xterm
    else
        echo "No terminal found" 2>&1
        exit 1
    fi
    eval 'exec "$xterm" -T buf $geometry -e' "$BUFFER_CMD"
else
    eval "$BUFFER_CMD"
fi
