#!/usr/bin/env bash
# Publish the single "Experimental" BlueGit release for experimental/tspl2.
#
# - Only on branch experimental/tspl2; fixed tag experimental-tspl2 (never X.Y.Z).
# - There is always at most one such release: an existing one is deleted
#   (with its tag and assets) before the new one is created.
# - Uses only CI_JOB_TOKEN. An existing release is replaced by BlueGit itself
#   ("replace": true): old release, assets and tag go, the new one takes the
#   same tag. BlueGit only allows that for a job on this (unprotected) branch,
#   started by a maintainer, for a release a job on this branch made. Without
#   replace the API would answer 409, so a second release is never created.
# - No AUR, no other secrets.
set -euo pipefail
: "${CI_API_URL:?}" "${CI_JOB_TOKEN:?}" "${CI_COMMIT_SHA:?}" "${CI_PROJECT_PATH:?}"
cd "$(dirname "$0")/../.."
TAG="experimental-tspl2"
BRANCH="experimental/tspl2"
[[ "${CI_COMMIT_BRANCH:-}" == "$BRANCH" ]] || { echo "Refusing: experimental release only from $BRANCH (got '${CI_COMMIT_BRANCH:-}')" >&2; exit 1; }
[[ ! "$TAG" =~ ^v?[0-9]+\.[0-9]+\.[0-9]+$ ]] || { echo "Refusing: version-like tag" >&2; exit 1; }
v="$(cat artifacts/version.txt)"
[[ "$v" == *-tspl2.* ]] || { echo "Refusing: not an experimental version: $v" >&2; exit 1; }
for f in dist/posprint-experimental-linux-x86_64.tar.gz dist/posprint-experimental-windows-x86_64.exe; do
  test -s "$f" || { echo "Missing artifact $f" >&2; exit 1; }
done

asset() { printf '{"job":"%s","path":"%s","name":"%s"}' "$1" "$2" "$3"; }
assets="$(asset exp:build:linux dist/posprint-experimental-linux-x86_64.tar.gz posprint-experimental-linux-x86_64.tar.gz),$(asset exp:build:windows dist/posprint-experimental-windows-x86_64.exe posprint-experimental-windows-x86_64.exe)"
short="${CI_COMMIT_SHA:0:8}"
desc="EXPERIMENTAL / PRERELEASE - niet stabiel, niet in AUR.\n\nVersie ${v} van branch ${BRANCH} (commit ${short}).\nTSPL/TSPL2-labelprinters (getest op opmaak, nog niet fysiek): protocol wordt automatisch herkend; labelformaat per printermodel.\n\n* Linux x86_64: posprint-experimental-linux-x86_64.tar.gz\n* Windows x86_64: posprint-experimental-windows-x86_64.exe\n\nDeze release wordt bij elke pipeline op ${BRANCH} vervangen."
body="$(printf '{"tag":"%s","commit":"%s","name":"%s","body":"%s","replace":true,"assets":[%s]}' "$TAG" "$CI_COMMIT_SHA" "Experimental: TSPL2 labelprinters (${v})" "$desc" "$assets")"
echo "Experimental release $TAG ($v) on $CI_COMMIT_SHA"
resp="$(mktemp)"
code="$(curl -sS -o "$resp" -w '%{http_code}' -X POST "$CI_API_URL/repos/$CI_PROJECT_PATH/releases" \
  -H "Authorization: Bearer $CI_JOB_TOKEN" -H "Content-Type: application/json" -d "$body")" || code=000
cat "$resp"; echo
[[ "$code" == 2* ]] || { echo "Release API returned HTTP $code" >&2; exit 1; }
