#!/bin/sh
# Simple sprunge.us pastebin client

have() {
	command -v "$1" >/dev/null 2>&1
}

now() {
	printf "%(%Y%m%d.%H%M%S)T"
}

seturl() {
	setfattr -n "user.sprunge-url" -v "$2" "$1" 2>/dev/null || :
}

getsel() {
	# too easy to put something important onto sprunge
	return
	if have xclip; then
		xclip -out -selection primary
	elif have xsel; then
		xsel -o -p
	else
		echo "no xclip nor xsel" >&2
		false
	fi
}

putclip() {
	if [ "$DISPLAY" ]; then
		if have xclip; then
			echo "$1" | xclip -in -selection clipboard
		elif have xsel; then
			echo "$1" | xsel -i -b
		fi
	fi
	putclip() { true; }
}

post() {
	local url=$(curl -sF "sprunge=<$1" http://sprunge.us/)
	if [ "$url" ]; then
		seturl "$1" $url
		echo $url
		putclip $url
	else
		echo "...failed"
	fi
}

cache=${XDG_CACHE_HOME:-$HOME/.cache}/sprunge

err=0
umask 077

if [ ! "$1" ] || [ "$*" = "-" ]; then
	# curl handles stdin buffering in a funny way, often
	# resulting in only the first write() to be pastebinned
	if [ -d "$cache" ]; then
		file="$cache/$(now).txt"
	else
		file=`mktemp /tmp/sprunge.XXXXXXXX`
	fi

	if [ ! "$1" ] && [ -t 0 ] && [ "$DISPLAY" ]; then
		getsel > "$file"
	else
		: > "$file"
	fi

	if [ ! -s "$file" ]; then
		if [ -t 0 ]; then
			printf "\e[1mInput text to pastebin:\e[m\n"
		fi
		cat > "$file"
		if [ -t 0 ]; then
			printf "\e[1mEOF\e[m\n"
		fi
	fi

	if [ -s "$file" ]; then
		post "$file"
		if [ ! -d "$cache" ]; then
			rm -f "$file"
		fi
	else
		echo "stdin: empty" >&2
		err=1
		rm -f "$file"
	fi
else
	for file; do
		if [ ! -f "$file" ]; then
			echo "$file: not a file" >&2
			err=1
		elif [ -s "$file" ]; then
			echo -n "$file → "
			post "$file"
		elif [ -e "$file" ]; then
			echo "$file: empty" >&2
			err=1
		else
			echo "$file: not found" >&2
			err=1
		fi
	done
fi

exit $err
