#!/usr/bin/env bash
# release.sh — publish a new version of the Thunderbird add-on to Gitea
# and update updates.json so installed clients auto-update.
#
# Prereqs:
#   - manifest.json "version" already bumped to the new version
#   - templates-reply-hotel.xpi rebuilt for that version, WITHOUT defaults.local.json
#     (the token must not ship in a public release; updates don't need defaults anyway)
#   - GITEA_TOKEN exported (a Gitea token with repo write access)
#
# Usage:  GITEA_TOKEN=xxxx ./release.sh
set -euo pipefail

OWNER="hps"
REPO="hps-thunderbird-templates"
BASE="https://git.hotel-park-soltau.de"
XPI="templates-reply-hotel.xpi"
ID="it@hotel-park-soltau.de"

cd "$(dirname "$0")"

# --- 0. Safety: never publish a build that bundles the local defaults/token ---
# Check the archive's file list (not raw bytes — the source references the
# filename as a string, which would be a false positive).
if 7z l "$XPI" | grep -q "defaults.local.json"; then
  echo "ABORT: $XPI contains defaults.local.json (your Gitea token!)." >&2
  echo "       Rebuild the .xpi without it before releasing." >&2
  exit 1
fi

VERSION=$(jq -r '.version' manifest.json)
MINVER=$(jq -r '.browser_specific_settings.gecko.strict_min_version' manifest.json)
TAG="v${VERSION}"
HASH=$(sha256sum "$XPI" | awk '{print $1}')
LINK="${BASE}/${OWNER}/${REPO}/releases/download/${TAG}/${XPI}"

echo "Version : $VERSION"
echo "Tag     : $TAG"
echo "SHA-256 : $HASH"

# --- 1. Rewrite updates.json: prepend this version (idempotent) ---
[ -f updates.json ] || echo "{\"addons\":{\"${ID}\":{\"updates\":[]}}}" > updates.json
TMP=$(mktemp)
jq --arg id "$ID" --arg v "$VERSION" --arg link "$LINK" \
   --arg hash "sha256:$HASH" --arg min "$MINVER" '
  .addons[$id].updates =
    ([{version:$v, update_link:$link, update_hash:$hash,
       applications:{gecko:{strict_min_version:$min}}}]
     + [ .addons[$id].updates[]? | select(.version != $v) ])
' updates.json > "$TMP" && mv "$TMP" updates.json
echo "updates.json updated"

# --- 2. Create the Gitea release + upload the .xpi asset ---
: "${GITEA_TOKEN:?Set GITEA_TOKEN to a Gitea token with repo write access}"
API="${BASE}/api/v1/repos/${OWNER}/${REPO}"
AUTH="Authorization: token ${GITEA_TOKEN}"

echo "Creating release $TAG ..."
REL_ID=$(curl -fsS -X POST "${API}/releases" \
  -H "$AUTH" -H "Content-Type: application/json" \
  -d "{\"tag_name\":\"${TAG}\",\"target_commitish\":\"main\",\"name\":\"${TAG}\"}" \
  | jq -r '.id')

echo "Uploading $XPI to release $REL_ID ..."
curl -fsS -X POST "${API}/releases/${REL_ID}/assets?name=${XPI}" \
  -H "$AUTH" -F "attachment=@${XPI};type=application/x-xpinstall" >/dev/null

echo
echo "Done. Now commit & push the manifest:"
echo "  git add updates.json manifest.json && git commit -m \"Release ${TAG}\" && git push"
