#!/usr/bin/env bash
# Génère build/release.json + empreinte SHA256 (à lancer après build-gcms-release.sh).
# Variables requises : VERSION, GCMS_RELEASE_BASE_URL (URL HTTPS du dossier, sans slash final),
# GCMS_RELEASE_PRIVATE_KEY_FILE (chemin PEM privé RSA).
# Optionnel : MIN_PHP (défaut 8.2), REQUIRES_COMPOSER (0 ou 1, défaut 0)
set -euo pipefail

ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
VERSION="${VERSION:?}"
ZIP="${ROOT}/build/gcms-${VERSION}.zip"
BASE_URL="${GCMS_RELEASE_BASE_URL:?}"
KEY="${GCMS_RELEASE_PRIVATE_KEY_FILE:?}"
MIN_PHP="${MIN_PHP:-8.2}"
REQ="${REQUIRES_COMPOSER:-0}"
REQ_PAYLOAD="0"
[[ "$REQ" == "1" ]] && REQ_PAYLOAD="1"

if [[ ! -f "$ZIP" ]]; then
  echo "ZIP introuvable : $ZIP" >&2
  exit 1
fi

SHA=$(sha256sum "$ZIP" | awk '{print tolower($1)}')
PKG_URL="${BASE_URL%/}/gcms-${VERSION}.zip"
ISSUED=$(date -u +%Y-%m-%dT%H:%M:%SZ)

PAYLOAD=$(printf '%s\n%s\n%s\n%s\n%s' "$VERSION" "$PKG_URL" "$SHA" "$MIN_PHP" "$REQ_PAYLOAD")
SIG=$(printf '%s' "$PAYLOAD" | openssl dgst -sha256 -sign "$KEY" -binary | base64 | tr -d '\n')

REQ_BOOL=false
[[ "$REQ" == "1" ]] && REQ_BOOL=true

jq -n \
  --arg v "$VERSION" \
  --arg url "$PKG_URL" \
  --arg sha "$SHA" \
  --arg min "$MIN_PHP" \
  --arg issued "$ISSUED" \
  --arg sig "$SIG" \
  --argjson req "$REQ_BOOL" \
  '{
    latest_version: $v,
    package_url: $url,
    sha256: $sha,
    min_php: $min,
    requires_composer: $req,
    issued_at: $issued,
    signature: $sig
  }' > "${ROOT}/build/release.json"

echo "OK : ${ROOT}/build/release.json"
echo "SHA256 zip : ${SHA}"
