#!/usr/bin/env bash
# Publish a signed APK as a Forgejo release so Obtainium can track it.
#
# Prereqs:
#   - A signed APK built at ./BigBrainParking-v<version>.apk (see docs/DISTRIBUTION.md)
#   - A Forgejo token with repo write scope, in $FORGEJO_TOKEN or .keys/forgejo.token
#     (create at: git.mowden.top -> Settings -> Applications -> Generate Token, scope: repository)
#
# Usage:  ./scripts/publish-release.sh
set -euo pipefail
cd "$(dirname "$0")/.."

REPO="hank/BigBrainParking"
API="https://git.mowden.top/api/v1"
TOKEN="${FORGEJO_TOKEN:-$(cat .keys/forgejo.token 2>/dev/null || true)}"
[ -n "$TOKEN" ] || { echo "ERROR: set FORGEJO_TOKEN or put a token in .keys/forgejo.token"; exit 1; }

VERSION="$(node -e "console.log(require('./app/app.json').expo.version)")"
TAG="v$VERSION"
APK="BigBrainParking-$TAG.apk"
[ -f "$APK" ] || { echo "ERROR: $APK not found — build a signed release first"; exit 1; }

echo "Publishing $TAG ($APK)…"

# Create the release (also creates the git tag on main if missing).
REL="$(curl -sf -X POST "$API/repos/$REPO/releases" \
  -H "Authorization: token $TOKEN" -H "Content-Type: application/json" \
  -d "{\"tag_name\":\"$TAG\",\"target_commitish\":\"main\",\"name\":\"BigBrainParking $TAG\",\"body\":\"Unofficial ParkSmarter client for GrapheneOS. Install/update via Obtainium.\"}")"
ID="$(printf '%s' "$REL" | node -e "let s='';process.stdin.on('data',d=>s+=d).on('end',()=>console.log(JSON.parse(s).id||''))")"
[ -n "$ID" ] || { echo "ERROR: release create failed: $REL"; exit 1; }

# Upload the APK asset.
curl -sf -X POST "$API/repos/$REPO/releases/$ID/assets?name=$APK" \
  -H "Authorization: token $TOKEN" -F "attachment=@$APK" >/dev/null

echo "✓ Published: https://git.mowden.top/$REPO/releases/tag/$TAG"
