#!/bin/bash
set -e

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

GITEA_TOKEN="eb44d9c0142f5038c61c5afd17f5a41177bfaedc"

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

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

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

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 thepool_${VERSION}_linux.tar.gz \
         thepool_${VERSION}_win32-x64.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 ==="
