#!/usr/bin/env sh
#
# Select a file and share it through 0x0.st
#
# Examples:
# `sharefile`
#   Calling without arguments allows you to first select a folder and then
#   a file from the folder to share.
# `sharefile ~/my-folder/`
#   Calling with a folder as argument restricts the file selection to files within.
# `sharefile ~/my-file.zip`
#   Calling with a file as argument automatically uploads the file and copies
#   share link to clipboard.
# `screenshot | sharefile -`
#   Calling with a dash as argument gets the file from stdin instead.
#   Be aware that this currently only works for files not folders.

OXO_URL="https://0x0.st"

# use fd if available
if command -v fd >/dev/null 2>&1; then
	sharefile_fd_cmd="fd"
else
	sharefile_fd_cmd="find"
fi

main() {
	if [ $# -eq 0 ]; then
		foldpick=$(picker d "")
		exit_check $?
		picked=$(picker f "$foldpick")
	elif [ "$1" = "-" ]; then
		while read -r file; do
			picked="$file"
		done <"/dev/stdin"
	elif [ -f "$1" ]; then
		picked="$1"
	elif [ -d "$1" ]; then
		picked=$(picker f "$1")
	else
		printf "Please only provide a folder or file as the optional argument to sharefile." >&2
		exit 1
	fi
	exit_check $?

	url=$(file_to_oxo "$picked")
	echo "$url"
	url_to_clipboard "$url"
	if command -v notify-send >/dev/null 2>&1; then
		notify-send "Upload finished" "URL: $url"
	fi
	exit
}

picker() {
	if [ "$sharefile_fd_cmd" = "fd" ]; then
		selected=$(fd "$SHAREFILE_FD_OPTS" --type "${1:-f}" . "${2:-$HOME}" | fzf)
	elif [ "$sharefile_fd_cmd" = "find" ]; then
		selected=$(find "$SHAREFILE_FD_OPTS" "${2:-$HOME}" -type "$1" | fzf)
	fi
	[ "$?" -eq 130 ] && exit 130
	echo "$selected"
}

url_to_clipboard() {
	if command -v wl-copy >/dev/null 2>&1; then
		printf "%s" "$@" | wl-copy
	elif command -v xsel >/dev/null 2>&1; then
		printf "%s" "$@" | xsel --clipboard
	elif command -v xclip >/dev/null 2>&1; then
		printf "%s" "$@" | xclip -selection clipboard >/dev/null 2>&1
	fi
}

file_to_oxo() {
	curl -F"file=@$1" "$OXO_URL"
}

# exit on escape pressed
exit_check() {
	[ "$1" -eq 130 ] && exit 130
}

main "$@"
