#!/usr/bin/env bash
# Compile le binaire release et publie une release Gitea avec le binaire en asset.
# Usage : ./deploy/release.sh v0.1.0
#         ./deploy/release.sh v0.1.1 "Description du changement"
set -euo pipefail

REPO_API="https://git.maison43gil.com/api/v1/repos/gilles/nano_metrics"
TOKEN_FILE="$(dirname "$0")/../repo.md"

# Lire le token depuis repo.md
TOKEN=$(grep -oP '(?<=\*\*Token\*\* : ).*' "$TOKEN_FILE" | tr -d '[:space:]')
if [ -z "$TOKEN" ]; then
    echo "ERREUR : token Gitea introuvable dans repo.md"
    exit 1
fi

TAG="${1:-}"
if [ -z "$TAG" ]; then
    echo "Usage : $0 <tag> [description]"
    echo "Exemple : $0 v0.1.0"
    exit 1
fi
DESCRIPTION="${2:-Release $TAG}"

ROOT="$(cd "$(dirname "$0")/.." && pwd)"
CARGO_TOML="$ROOT/agent/Cargo.toml"

mkdir -p "$ROOT/dist"

# ── 1. Compiler l'agent pour toutes les cibles supportées ────────────────
echo "=== Compilation de l'agent ==="
TARGETS=("x86_64-unknown-linux-musl" "aarch64-unknown-linux-musl")
LABELS=("linux-amd64" "linux-arm64")

mkdir -p "$ROOT/dist"

for i in "${!TARGETS[@]}"; do
    TARGET="${TARGETS[$i]}"
    LABEL="${LABELS[$i]}"
    echo "→ $TARGET ($LABEL)..."

    # Installer la cible si absente
    rustup target add "$TARGET" 2>/dev/null || true

    # Compiler (CC requis par la crate ring pour les cibles musl cross)
    CC_aarch64_unknown_linux_musl=aarch64-linux-gnu-gcc \
    AR_aarch64_unknown_linux_musl=aarch64-linux-gnu-ar \
    cargo build --release \
        --manifest-path "$CARGO_TOML" \
        --target "$TARGET" \
        2>&1 | tail -3

    SRC="$ROOT/agent/target/$TARGET/release/nanometrics-agent"
    if [ ! -f "$SRC" ]; then
        echo "  AVERTISSEMENT : binaire introuvable pour $TARGET, ignoré"
        continue
    fi

    DEST="$ROOT/dist/nanometrics-agent-$LABEL"
    cp "$SRC" "$DEST"
    strip "$DEST" 2>/dev/null || true
    echo "  OK : $(du -sh "$DEST" | cut -f1)"
done

# ── 2. Créer la release Gitea ──────────────────────────────────────────────
echo ""
echo "=== Création de la release Gitea $TAG ==="

RELEASE_JSON=$(curl -sf \
    -H "Authorization: token $TOKEN" \
    -H "Content-Type: application/json" \
    -X POST "$REPO_API/releases" \
    -d "{
        \"tag_name\": \"$TAG\",
        \"name\": \"$TAG\",
        \"body\": \"$DESCRIPTION\",
        \"draft\": false,
        \"prerelease\": false
    }")

RELEASE_ID=$(echo "$RELEASE_JSON" | python3 -c "import sys,json; print(json.load(sys.stdin)['id'])")
echo "Release ID : $RELEASE_ID"

# ── 3. Uploader les binaires comme assets ─────────────────────────────────
echo ""
echo "=== Upload des binaires ==="

for LABEL in "${LABELS[@]}"; do
    ASSET="$ROOT/dist/nanometrics-agent-$LABEL"
    [ -f "$ASSET" ] || continue

    ASSET_NAME="nanometrics-agent-$LABEL"
    echo "→ Upload $ASSET_NAME..."

    curl -sf \
        -H "Authorization: token $TOKEN" \
        -F "attachment=@$ASSET;filename=$ASSET_NAME" \
        "$REPO_API/releases/$RELEASE_ID/assets" \
        > /dev/null

    echo "  OK"
done

echo ""
echo "✓ Release $TAG publiée : https://git.maison43gil.com/gilles/nano_metrics/releases/tag/$TAG"
