#!/bin/sh
# Publish a signed release APK to a Codeberg (Forgejo) release. Run on a tag,
# after ci/build.sh has produced a signed app-release.apk (signing happens when
# keystore.properties is present).
#
# Environment:
#   CODEBERG_TOKEN  Forgejo API token (secret)
#   CODEBERG_REPO   owner/name, e.g. lena/rsend
#   TAG             release tag (defaults to CI_COMMIT_TAG)
#   CODEBERG_URL    base URL (defaults to https://codeberg.org)
set -eu

: "${CODEBERG_TOKEN:?set CODEBERG_TOKEN}"
: "${CODEBERG_REPO:?set CODEBERG_REPO as owner/name}"
tag=${TAG:-${CI_COMMIT_TAG:?set TAG or CI_COMMIT_TAG}}
base=${CODEBERG_URL:-https://codeberg.org}
apk=app/build/outputs/apk/release/app-release.apk

[ -f "$apk" ] || { echo "release: $apk not found; run ci/build.sh first" >&2; exit 1; }

api="$base/api/v1/repos/$CODEBERG_REPO"

# Create the release for the tag and capture its id.
id=$(curl -fsS -X POST "$api/releases" \
	-H "Authorization: token $CODEBERG_TOKEN" \
	-H "Content-Type: application/json" \
	-d "{\"tag_name\":\"$tag\",\"name\":\"$tag\"}" \
	| sed -n 's/.*"id":\([0-9][0-9]*\).*/\1/p' | head -1)
[ -n "$id" ] || { echo "release: could not create release for $tag" >&2; exit 1; }

# Upload the APK as a release asset.
curl -fsS -X POST "$api/releases/$id/assets?name=rsend-$tag.apk" \
	-H "Authorization: token $CODEBERG_TOKEN" \
	-F "attachment=@$apk" >/dev/null

echo "release: uploaded rsend-$tag.apk to $CODEBERG_REPO ($tag)"
