#!/usr/bin/env bash
# Captures a region screenshot, pushes it to scrot as a `shot` blob, and
# copies the returned public link to the clipboard.
set -euo pipefail

: "${SCROT_SERVER:?set SCROT_SERVER, e.g. https://scrot.example.com}"
: "${DEVICE_TOKEN:?set DEVICE_TOKEN}"

tmpfile=$(mktemp --suffix=.png)
trap 'rm -f "$tmpfile"' EXIT

if [ -n "${WAYLAND_DISPLAY:-}" ]; then
  grim -g "$(slurp)" "$tmpfile"
else
  maim -s "$tmpfile"
fi

response=$(curl -sf -X POST "$SCROT_SERVER/api/blobs" \
  -H "X-Device-Token: $DEVICE_TOKEN" \
  -H "X-Blob-Kind: shot" \
  -H "Content-Type: image/png" \
  --data-binary "@$tmpfile")

url=$(printf '%s' "$response" | grep -o '"url":"[^"]*"' | cut -d'"' -f4)
full_url="$SCROT_SERVER$url"

if [ -n "${WAYLAND_DISPLAY:-}" ]; then
  printf '%s' "$full_url" | wl-copy
else
  printf '%s' "$full_url" | xclip -selection clipboard
fi

echo "screenshot uploaded: $full_url"
