#!/usr/bin/env bash
# Fetches the latest `clip` blob from scrot and writes it into the local
# system clipboard.
set -euo pipefail

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

response=$(curl -sf -w '\n%{http_code}' "$SCROT_SERVER/api/clip/latest" \
  -H "X-Device-Token: $DEVICE_TOKEN")

status="${response##*$'\n'}"
body="${response%$'\n'*}"

if [ "$status" = "204" ]; then
  echo "no clip yet" >&2
  exit 1
fi

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

echo "clip pulled into clipboard"
