#!/bin/bash
set -e

#if [ -z "$1" ]; then
#    echo "Uso: $0 <PARAMETRO>"
#    exit 1
#fi

#GITEA_TOKEN="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"

if [ -z "$GITEA_TOKEN" ]; then
    echo "ERROR: Debes exportar GITEA_TOKEN"
    exit 1
fi

# Leer versión desde version.h
VERSION=$(grep '#define MINI_VERSION' source/mini/version.h | sed 's/.*"\(.*\)".*/\1/')
echo "Versión detectada: $VERSION"

#PARAM=$1
API="https://gitea.sustancia.synology.me/api/v1"
REPO="JailDoctor/mini"

echo "=== Creando release ${VERSION} en Gitea ==="

RELEASE_ID=$(curl -s -X POST "${API}/repos/${REPO}/releases" \
  -H "Authorization: token ${GITEA_TOKEN}" \
  -H "Content-Type: application/json" \
  -d "{
        \"tag_name\": \"${VERSION}\",
        \"name\": \"Release ${VERSION}\",
        \"draft\": false,
        \"prerelease\": false
      }" | jq -r '.id')

if [ "$RELEASE_ID" = "null" ]; then
    echo "ERROR: No se pudo crear el release"
    exit 1
fi

echo "Release creado con ID: $RELEASE_ID"

echo "=== Subiendo artefactos ==="

for f in mini_v${VERSION}_linux_release.tar.gz \
         mini_v${VERSION}_linux_debug.tar.gz \
         mini_v${VERSION}_win32-x64_release.zip \
         mini_v${VERSION}_win32-x64_debug.zip
do
    echo "Subiendo $f..."
    curl -s -X POST \
        -H "Authorization: token ${GITEA_TOKEN}" \
        -F "attachment=@${f}" \
        "${API}/repos/${REPO}/releases/${RELEASE_ID}/assets" > /dev/null
done

echo "=== Publicación completada ==="
