#!/bin/bash
# Script to upload release artifacts to Gitea
# Usage: ./scripts/upload-release.sh <tag> <gitea_token>

set -e

TAG="${1:?Tag is required (e.g., v1.0.0)}"
GITEA_TOKEN="${2:?Gitea API token is required}"
GITEA_URL="${GITEA_URL:-https://git.nerdnest.dev}"
REPO_OWNER="${REPO_OWNER:-ducky}"
REPO_NAME="${REPO_NAME:-nerd-monitor}"
BIN_DIR="./bin"

if [ ! -d "$BIN_DIR" ]; then
    echo "Error: $BIN_DIR directory not found"
    exit 1
fi

# Get or create release
echo "Getting release info for tag: $TAG"
RELEASE_JSON=$(curl -s -X GET \
    -H "Authorization: token $GITEA_TOKEN" \
    "$GITEA_URL/api/v1/repos/$REPO_OWNER/$REPO_NAME/releases/tags/$TAG" 2>/dev/null || echo "{}")

RELEASE_ID=$(echo "$RELEASE_JSON" | jq -r '.id // empty' 2>/dev/null)

if [ -z "$RELEASE_ID" ]; then
    echo "Creating new release for tag: $TAG"
    RELEASE_JSON=$(curl -s -X POST \
        -H "Authorization: token $GITEA_TOKEN" \
        -H "Content-Type: application/json" \
        -d "{\"tag_name\":\"$TAG\",\"name\":\"Release $TAG\",\"draft\":false,\"prerelease\":false}" \
        "$GITEA_URL/api/v1/repos/$REPO_OWNER/$REPO_NAME/releases")
    RELEASE_ID=$(echo "$RELEASE_JSON" | jq -r '.id')
fi

echo "Release ID: $RELEASE_ID"

# Upload all binaries
echo "Uploading release artifacts..."
for file in "$BIN_DIR"/*; do
    if [ -f "$file" ]; then
        filename=$(basename "$file")
        echo "  Uploading: $filename"
        
        curl -s -X POST \
            -H "Authorization: token $GITEA_TOKEN" \
            -F "attachment=@$file" \
            "$GITEA_URL/api/v1/repos/$REPO_OWNER/$REPO_NAME/releases/$RELEASE_ID/assets" > /dev/null
        
        echo "    ✓ $filename uploaded"
    fi
done

echo ""
echo "Release created/updated successfully!"
echo "View at: $GITEA_URL/$REPO_OWNER/$REPO_NAME/releases/tag/$TAG"
