#!/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() { jq -n --arg j "$1" --arg p "$2" --arg n "$3" '{job:$j,path:$p,name:$n}'; }
assets="$(jq -s . \
  <(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"))"
desc="Paperdoll Renderer ${version}.

* Linux AppImage (portable).
* Debian/Ubuntu .deb: /usr/bin/paperdoll-renderer, desktop entry, icons, .ppd MIME type.
* Arch .pkg.tar.zst, built from packaging/arch/PKGBUILD. AUR: paperdoll-renderer-bin.
* Windows zip (x86_64, MinGW build).
* SHA256SUMS of the package files.

The 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="$(jq -n --arg n "Paperdoll Renderer ${tag}" --arg b "$desc" --argjson a "$assets" '{name:$n,body:$b,assets:$a}')"

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
