#!/usr/bin/env bash
# Upload ONE file to R2 with the right content-type + immutable cache. Used by
# deploy.sh's parallel xargs (wrangler has no bulk sync). Reads BUCKET / MEDIA_OUT /
# WRANGLER from the environment; the single argument is the local file path.
set -u
f="$1"
key="${f#"$MEDIA_OUT"/}"
# Guard: if the prefix strip didn't fire (e.g. relative path vs absolute MEDIA_OUT),
# the key would wrongly keep a leading dir → wrong R2 path. Fail loudly, don't ship it.
if [ "$key" = "$f" ]; then
  echo "FAIL $f  (key strip failed — MEDIA_OUT='$MEDIA_OUT' is not a prefix; pass absolute paths)"
  exit 1
fi
case "${f##*.}" in
  mp4) ct=video/mp4 ;;
  mp3) ct=audio/mpeg ;;
  json) ct=application/json ;;
  *) ct=application/octet-stream ;;
esac
if "$WRANGLER" r2 object put "$BUCKET/$key" --file "$f" --remote \
     --content-type "$ct" --cache-control "public, max-age=31536000, immutable" >/dev/null 2>&1; then
  echo "ok   $key"
else
  echo "FAIL $key"
fi
