#!/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"
auth="Authorization: token $CODEBERG_TOKEN"
name="rsend-$tag.apk"

# Reuse the tag's release if it exists, else create it. Re-runs are idempotent:
# same release, and a stale asset from an earlier run is replaced below.
id=$(curl -fsS -H "$auth" "$api/releases/tags/$tag" 2>/dev/null \
	| python3 -c 'import json,sys; print(json.load(sys.stdin)["id"])' 2>/dev/null) || id=
if [ -n "$id" ]; then
	curl -fsS -H "$auth" "$api/releases/$id/assets" \
		| python3 -c 'import json,sys
for a in json.load(sys.stdin):
	if a["name"] == sys.argv[1]:
		print(a["id"])' "$name" \
		| while read -r aid; do
			curl -fsS -X DELETE -H "$auth" "$api/releases/$id/assets/$aid"
		done
else
	id=$(curl -fsS -X POST "$api/releases" \
		-H "$auth" -H "Content-Type: application/json" \
		-d "{\"tag_name\":\"$tag\",\"name\":\"$tag\"}" \
		| python3 -c 'import json,sys; print(json.load(sys.stdin)["id"])')
fi
[ -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=$name" \
	-H "$auth" \
	-F "attachment=@$apk" >/dev/null

echo "release: uploaded $name to $CODEBERG_REPO ($tag)"
