#!/usr/bin/env sh

tool="grim"

rclone_remote="s3-serguzim-me:public/screenshots"
screenshot_host="https://s3.serguzim.me/public/screenshots"
screenshot_path="/tmp/screenshot.webp"
file="$(date '+%F_%H-%M-%S').webp"

clip_image()
{
	if [ -n "$WAYLAND_DISPLAY" ]
	then
		wl-copy -t image/png < "$screenshot_path"
	else
		xclip -t image/png "$screenshot_path" -selection clipboard
	fi
}

upload_image()
{
	# to have link available in clipboard manager
	if [ -n "$WAYLAND_DISPLAY" ]
	then
		wl-copy "$screenshot_host/$file"
		wl-copy -p "$screenshot_host/$file"
	else
		printf '%s' "$screenshot_host/$file" | xclip -selection clipboard
		printf '%s' "$screenshot_host/$file" | xclip -selection primary
	fi

    rclone copyto "$screenshot_path" "$rclone_remote/$file"
    notify-send -a "Screenshot" "Uploaded screenshot to s3"
}

call_screenshot_tool() {
	case $tool in
		flameshot)
			result=$(flameshot gui -r | tee $screenshot_path | wc -c) ;;
		grim)
			result=$(grim -g "$(slurp)" - | tee $screenshot_path | wc -c) ;;
		*)
			echo "Unknown screenshot tool: $tool"
			return 1 ;;
	esac

	if [ "$result" -gt 0 ]
	then
		return 0
	else
		return 1
	fi
}

main_no_upload()
{
	if call_screenshot_tool
    then
        clip_image
    fi
}

main()
{
    if [ -n "$1" ] && [ -e "$1" ]
    then
        convert "$1" "$screenshot_path"
        upload_image
        clip_image
    else
		if call_screenshot_tool
        then
            upload_image
            clip_image
        fi
    fi
}

case $1 in
    no_upload)   main_no_upload ;;
    *)           main "$1" ;;
esac