#!/bin/sh -eu
#
# srht - Upload files/scrots/urls to sr.ht (rip pomf & uguu)
# By onodera, modified by SirCmpwn

## CONFIGURATION
. ~/.config/srht

## FUNCTIONS

sway_output() {
	swaymsg -rt get_workspaces | jq -r '.[] | select(.focused).output'
}

# This function sets $file to a selection scrot
selection() {
	uploadme="/tmp/scrot.""$screenshot_extension"

	if [ -n "$SWAYSOCK" ]
	then
		grim -g "$(slurp -db '#44444480')" "$uploadme"
	else
		maim --hidecursor -s -b 3 -c 250,250,250 "$uploadme" 2> "/dev/null"
	fi
	if [ "$?" -ge 1 ]; then
		echo "Selection cancelled."
		exit 1
	fi

	word=selection
}

# This function sets $file an url
url() {
	type="$(echo "$location" | rev | cut -d "." -f 1 | rev)"
	uploadme="/tmp/url.$type"

	wget --quiet "$location" -O "$uploadme"

	word=url
}

# This function sets $file a file
file() {
	if [ -f "$location" ]; then
		uploadme="$location"
	else
		echo "File not found."
		exit 1
	fi

	word=file
}

# This function sets $file to a full screen scrot
desktop() {
	uploadme="/tmp/scrot.""$screenshot_extension"

	if [ -n "$SWAYSOCK" ]; then
		grim -o $(sway_output) "$uploadme"
	else
		maim --hidecursor "$uploadme"
	fi

	word=desktop
}

# This function uploads the $file
upload() {
	url="$(curl --silent -H Authorization:"token $key" -F file="@$uploadme" "https://l.sr.ht/api/upload" | grep -o -i "https://l.sr.ht/*.[a-z0-9._-]*")"
}

# This function logs the url,  copies the url to the clipboard, and/or opens the url in your browser
feedback() {
	# Copy url to clipboard
	if [ "$clipboard" = "true" ]; then
		printf "$url" | wl-copy
	fi

	# Log url
	if [ "$log" = "true" ]; then
		echo "$url" >> "$logfile"
	fi

	# Open url in browser
	if [ "$browser" == true ]; then
		xdg-open "$url"
	fi

	# Send notification
	if [ "$notify" == true ]; then
		notify-send "Upload complete: $url"
	fi

	echo "$url"
}

## EXECUTE

if [ "$#" -ge 1 ]
then
	case "$@" in
		-h|--help)
			echo "usage: srht [options] [file/url]"
			echo "options:"
			echo "  -h,   --help            print help and exit"
			echo "  -p,   --paste       	upload your clipboard as text"
			echo "  -s,   --selection       upload selection scrot"
			echo "  -v,   --version         print version and exit"
			exit 0
			;;
		-s|--selection)
			selection
			;;
		-v|--version)
			echo "srht 0.9.1"
			exit 0
			;;
		http*)
			location="$@"
			url
			;;
		*)
			location="$@"
			file
			;;
	esac
else
	desktop
fi


if [ "$#" -eq 0 ]; then
	desktop
fi

upload
feedback
