#!/usr/bin/env bash
# Create the BlueGit release on CI_COMMIT_SHA with the build artifacts as
# assets. The release API creates the tag itself (bare version, e.g. 0.5.9).
set -euo pipefail
: "${CI_API_URL:?}" "${CI_JOB_TOKEN:?}" "${CI_COMMIT_SHA:?}" "${CI_PROJECT_PATH:?}"
cd "$(dirname "$0")/../.."
v="$(cat artifacts/version.txt)"
[[ "$v" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]] || { echo "Invalid version: $v" >&2; exit 1; }
now="$(bash scripts/ci/next-version.sh)"
[[ "$now" == "$v" ]] || { echo "Version $v is already taken (next is $now). Rerun the pipeline." >&2; exit 1; }
asset() { printf '{"job":"%s","path":"%s","name":"%s"}' "$1" "$2" "$3"; }
assets="$(asset build:linux-deb "dist/posprint_${v}-1_amd64.deb" "posprint_${v}-1_amd64.deb"),$(asset build:linux-arch "dist/posprint-${v}-1-x86_64.pkg.tar.zst" "posprint-${v}-1-x86_64.pkg.tar.zst"),$(asset build:linux-arch "dist/posprint-${v}-x86_64.tar.gz" "posprint-${v}-x86_64.tar.gz"),$(asset build:windows dist/posprint.exe posprint.exe)"
desc='* Debian/Ubuntu: posprint_<version>-1_amd64.deb\n* Arch: posprint-<version>-1-x86_64.pkg.tar.zst\n* Linux binary tarball (AUR posprint-bin): posprint-<version>-x86_64.tar.gz\n* Windows: posprint.exe\n\nAUR: posprint, posprint-bin.'
body="$(printf '{"tag":"%s","commit":"%s","name":"posprint %s","body":"%s","assets":[%s]}' "$v" "$CI_COMMIT_SHA" "$v" "$desc" "$assets")"
echo "Release $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; }
