#!/bin/bash
# Upload PaddlePaddle ARM64 wheel to Gitea generic packages
#
# Usage:
#   ./scripts/upload-wheel.sh [wheel_file] [token]
#
# Environment variables (alternative to arguments):
#   GITEA_TOKEN - Gitea API token
#   WHEEL_FILE  - Path to wheel file (default: auto-detect in wheels/)

set -e

GITEA_URL="https://seryus.ddns.net"
GITEA_ORG="unir"
PACKAGE_NAME="paddlepaddle-gpu-arm64"

# Get wheel file
WHEEL_FILE="${1:-${WHEEL_FILE:-$(ls wheels/paddlepaddle*.whl 2>/dev/null | head -1)}}"
if [ -z "$WHEEL_FILE" ] || [ ! -f "$WHEEL_FILE" ]; then
    echo "Error: No wheel file found"
    echo "Usage: $0 [wheel_file] [token]"
    echo "  or set WHEEL_FILE environment variable"
    exit 1
fi

# Get token
TOKEN="${2:-${GITEA_TOKEN}}"
if [ -z "$TOKEN" ]; then
    echo "Error: No token provided"
    echo "Usage: $0 [wheel_file] [token]"
    echo "  or set GITEA_TOKEN environment variable"
    exit 1
fi

# Extract version from wheel filename
# Format: paddlepaddle_gpu-3.0.0-cp311-cp311-linux_aarch64.whl
FILENAME=$(basename "$WHEEL_FILE")
VERSION=$(echo "$FILENAME" | sed -E 's/paddlepaddle[_-]gpu-([0-9.]+)-.*/\1/')

if [ -z "$VERSION" ]; then
    echo "Error: Could not extract version from filename: $FILENAME"
    exit 1
fi

echo "Uploading wheel to Gitea packages..."
echo "  File: $WHEEL_FILE"
echo "  Package: $PACKAGE_NAME"
echo "  Version: $VERSION"
echo "  URL: $GITEA_URL/api/packages/$GITEA_ORG/generic/$PACKAGE_NAME/$VERSION/$FILENAME"

# Upload using PUT request
HTTP_CODE=$(curl -sS -w "%{http_code}" -o /tmp/upload_response.txt \
    -X PUT \
    -H "Authorization: token $TOKEN" \
    -H "Content-Type: application/octet-stream" \
    --data-binary "@$WHEEL_FILE" \
    "$GITEA_URL/api/packages/$GITEA_ORG/generic/$PACKAGE_NAME/$VERSION/$FILENAME")

if [ "$HTTP_CODE" = "201" ] || [ "$HTTP_CODE" = "200" ]; then
    echo "Success! Wheel uploaded."
    echo "Download URL: $GITEA_URL/api/packages/$GITEA_ORG/generic/$PACKAGE_NAME/$VERSION/$FILENAME"
elif [ "$HTTP_CODE" = "409" ]; then
    echo "Package version already exists (HTTP 409)"
    echo "To update, delete the existing version first in Gitea UI"
else
    echo "Error: Upload failed with HTTP $HTTP_CODE"
    cat /tmp/upload_response.txt
    exit 1
fi
