#!/bin/sh
# End-to-end smoke test against a running defter backed by real S3 storage
# (e.g. RustFS, see README "Development"). Walks the Zotero file protocol:
# create an attachment item, authorize, upload, register, then download
# through the pre-signed URL the server redirects to.
#
#   DEFTER_URL=http://127.0.0.1:8189 DEFTER_KEY=... scripts/smoke-s3.sh
set -eu

URL=${DEFTER_URL:-http://127.0.0.1:8189}
KEY=${DEFTER_KEY:?set DEFTER_KEY to a read/write API key}
API="$URL/api/users/0"
TMP=$(mktemp -d)
trap 'rm -rf "$TMP"' EXIT

head -c 300000 /dev/urandom >"$TMP/file.pdf"
MD5=$(md5 -q "$TMP/file.pdf" 2>/dev/null || md5sum "$TMP/file.pdf" | cut -d' ' -f1)
SIZE=$(wc -c <"$TMP/file.pdf" | tr -d ' ')

echo "server: $(curl -sf -D - -o /dev/null "$URL/api/" | grep -i '^zotero-server-id' | tr -d '\r')"

ITEM=$(curl -sf -H "Zotero-API-Key: $KEY" -H 'Content-Type: application/json' \
  -d '[{"itemType":"attachment","linkMode":"imported_file","title":"Smoke test","filename":"smoke.pdf","contentType":"application/pdf"}]' \
  "$API/items" | jq -r '.successful["0"].key')
echo "item: $ITEM"

AUTH=$(curl -sf -H "Zotero-API-Key: $KEY" -H 'If-None-Match: *' \
  --data-urlencode "md5=$MD5" --data-urlencode "filename=smoke.pdf" \
  --data-urlencode "filesize=$SIZE" --data-urlencode "mtime=1700000000000" \
  "$API/items/$ITEM/file")
UPLOAD_URL=$(echo "$AUTH" | jq -r .url)
UPLOAD_KEY=$(echo "$AUTH" | jq -r .uploadKey)

STATUS=$(curl -s -o /dev/null -w '%{http_code}' -H 'Content-Type: application/pdf' \
  --data-binary "@$TMP/file.pdf" "$UPLOAD_URL")
echo "upload: HTTP $STATUS"
[ "$STATUS" = 201 ]

STATUS=$(curl -s -o /dev/null -w '%{http_code}' -H "Zotero-API-Key: $KEY" -H 'If-None-Match: *' \
  --data-urlencode "upload=$UPLOAD_KEY" "$API/items/$ITEM/file")
echo "register: HTTP $STATUS"
[ "$STATUS" = 204 ]

LOCATION=$(curl -s -o /dev/null -w '%{redirect_url}' -H "Zotero-API-Key: $KEY" "$API/items/$ITEM/file")
echo "download: ${LOCATION%%\?*}"
curl -sf -o "$TMP/back.pdf" "$LOCATION"
cmp "$TMP/file.pdf" "$TMP/back.pdf"
echo "ok: $SIZE bytes round-tripped through object storage"

VERSION=$(curl -sf -D - -o /dev/null -H "Zotero-API-Key: $KEY" "$API/items/$ITEM" |
  grep -i '^last-modified-version' | tr -dc '0-9')
curl -sf -X DELETE -H "Zotero-API-Key: $KEY" -H "If-Unmodified-Since-Version: $VERSION" "$API/items/$ITEM"
echo "cleaned up item $ITEM"
