#!/usr/bin/env bash
# Tag-pipeline publish step (design.md, "v0.1.0 release" decision).
#
# Publishes the release for the tag that started this pipeline with
# POST $CI_API_URL/repos/{owner}/{repo}/releases/{tag}/assets — BlueGit's
# create-only route for an existing tag: an existing release is HTTP 409, it
# never creates, moves or deletes the tag, and the assets are artifacts of
# successful jobs of this same pipeline. `replace` is never sent and the
# tag-creating route POST .../releases is never called.
set -euo pipefail

: "${CI_API_URL:?}" "${CI_JOB_TOKEN:?}" "${CI_COMMIT_SHA:?}" "${CI_PROJECT_PATH:?}" "${CI_COMMIT_TAG:?}"

root="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
cd "$root"
version="$(bash scripts/ci/package-version.sh)"
tag="$CI_COMMIT_TAG"
[[ "$tag" == "v$version" ]] || { echo "tag $tag does not match package version $version" >&2; exit 1; }

b="paperdoll-renderer-${tag}"
asset() { printf '{"job":"%s","path":"%s","name":"%s"}' "$1" "$2" "$3"; }
assets="$(asset package:appimage dist/paperdoll-renderer-x86_64.AppImage "${b}-x86_64.AppImage"),$(asset package:ubuntu dist/paperdoll-renderer_amd64.deb "${b}-amd64.deb"),$(asset package:arch dist/paperdoll-renderer-x86_64.pkg.tar.zst "${b}-x86_64.pkg.tar.zst"),$(asset package:windows dist/paperdoll-renderer-windows-x86_64.zip "${b}-windows-x86_64.zip"),$(asset verify:packages dist/SHA256SUMS "${b}-SHA256SUMS.txt")"
# JSON-escaped already (\n, no double quotes inside).
desc="Paperdoll Renderer ${version}.\n\n* Linux AppImage (portable).\n* Debian/Ubuntu .deb: /usr/bin/paperdoll-renderer, desktop entry, icons, .ppd MIME type.\n* Arch .pkg.tar.zst, built from packaging/arch/PKGBUILD. AUR: paperdoll-renderer-bin.\n* Windows zip (x86_64, MinGW build).\n* SHA256SUMS of the package files.\n\nThe default starter bodies are Animated walking Male Base Mesh and Animated Female Base Mesh by assetfactory (Sketchfab Standard licence); see THIRD_PARTY_NOTICES.md."
body="$(printf '{"name":"Paperdoll Renderer %s","body":"%s","assets":[%s]}' "$tag" "$desc" "$assets")"

echo "Release $tag on $CI_COMMIT_SHA (existing tag, create-only)"
resp="$(mktemp)"
code="$(curl -sS -o "$resp" -w '%{http_code}' -X POST \
  "$CI_API_URL/repos/$CI_PROJECT_PATH/releases/$tag/assets" \
  -H "Authorization: Bearer $CI_JOB_TOKEN" -H "Content-Type: application/json" -d "$body")" || code=000
cat "$resp"; echo
if [[ "$code" != 2* ]]; then
  echo "release API returned HTTP $code (see response above)" >&2
  exit 1
fi
