#!/usr/bin/env bash
# sprunge -- upload text to a pastebin
#
# Originally for sprunge.us, which has since died.

. lib.bash || exit

post() {
	local file=$1 newname=${2:-${1##*/}}
	echo -n "$file → "
	local url=$(upload -q -0 -d txt -S "s/.*/$newname/" "$file")
	if [ "$url" ]; then
		echo $url
		if gclip -q &> /dev/null; then
			printf '%s' "$*" | gclip
		fi
	else
		err "upload failed"
	fi
}

filename() {
	printf "%(%Y%m%d.%H%M%S)T.XXXXXX.txt"
}

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

umask 077

if [ ! "$1" ] || [ "$*" = "-" ]; then
	if [ -d "$cache" ]; then
		file=$(mktemp "$cache/$(filename)")
	else
		file=$(mktemp "/tmp/sprunge.$(filename)")
	fi

	dstname=$(basename "$file")
	dstname=${dstname#sprunge.}

	if [ ! "$1" ] && [ -t 0 ] && psel -q &> /dev/null; then
		psel > "$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" "$dstname"
		if [ ! -d "$cache" ]; then
			rm -f "$file"
		fi
	else
		err "stdin: empty"
		rm -f "$file"
	fi
else
	for file; do
		if [ ! -f "$file" ]; then
			err "$file: not a file"
		elif [ -s "$file" ]; then
			post "$file" "$(mktemp -u "$(filename)")"
		elif [ -e "$file" ]; then
			err "$file: empty"
		else
			err "$file: not found"
		fi
	done
fi

((!errors))
