#!/bin/sh
# release-dist.sh - build + publish the six dist targets for this plugin.
#
# The cross-target build, the dist upload and the plugingit mirror all live in
# scorpiox-cli-botplugin (it owns the musl / aarch64 / MinGW toolchains and the
# macOS builder). This wrapper exists so the release is repeatable and so an
# audit failure stops it before anything is published.
#
#   ./release-dist.sh                 # publish the version in plugin.json
#   VERSION=1.0.1 ./release-dist.sh   # explicit version
#
# Run it on the build host that has musl-gcc, aarch64-linux-gnu-gcc,
# x86_64-w64-mingw32-gcc and ssh access to the macOS builder.
#
# SSHPASS must be exported: without it the macOS leg answers
# "build: macOS skipped: SSHPASS not set" and the dist upload fails, while the
# run still prints "build ok: <slug> (4 target(s) built)". Always read the
# target count out of latest.json afterwards - it must be 6.

set -eu

SLUG=webhook
ROOT=$(cd "$(dirname "$0")" && pwd)
VERSION="${VERSION:-$(python3 -c 'import json,sys;print(json.load(open("'"$ROOT"'/plugin.json"))["version"])')}"
# A private address must never be written into this public repository (the
# history scanner refuses it, and rightly so), so the builder is supplied by the
# environment rather than defaulted here.
MACOS_HOST="${MACOS_HOST:?set MACOS_HOST to user@mac-builder (sshd with SSHPASS)}"

if ! command -v scorpiox-cli-botplugin >/dev/null 2>&1; then
    echo "scorpiox-cli-botplugin not found on PATH" >&2
    exit 1
fi

echo "==> audit $SLUG"
scorpiox-cli-botplugin audit "$ROOT" --json || { echo "audit blocked the release" >&2; exit 4; }

echo "==> publish $SLUG $VERSION"
scorpiox-cli-botplugin publish "$ROOT" \
    --slug "$SLUG" \
    --version "$VERSION" \
    --macos-host "$MACOS_HOST" \
    --json

echo "==> reindex"
scorpiox-cli-botplugin reindex --json >/dev/null 2>&1 || true

echo "==> check the target count (must be 6)"
curl -s "https://dist.scorpiox.net/bot-plugins/$SLUG/latest.json" |
    python3 -c 'import json,sys; d=json.load(sys.stdin); t=d.get("targets",{}); print("version", d.get("version"), "targets", len(t)); sys.exit(0 if len(t)==6 else 1)'
