#!/usr/bin/env bash
set -euo pipefail

# === CONFIGURATION ===
OWNER="REG-Linux"
REPO="REG-Linux"
TAG="25.09-preview"
GITHUB_TOKEN="${GITHUB_TOKEN:-}"

# === CHECKS ===
if [[ -z "$GITHUB_TOKEN" ]]; then
    echo "❌ Error: GITHUB_TOKEN environment variable not set."
    echo "Usage: GITHUB_TOKEN=your_token ./upload-imgs-to-github.sh"
    exit 1
fi

# === GET RELEASE INFO ===
echo "🔍 Fetching release info for tag '$TAG'..."
API_URL="https://api.github.com/repos/${OWNER}/${REPO}/releases/tags/${TAG}"
RELEASE_JSON=$(curl -s -H "Authorization: token ${GITHUB_TOKEN}" "$API_URL")

UPLOAD_URL=$(echo "$RELEASE_JSON" | jq -r '.upload_url' | sed 's/{?name,label}//')
RELEASE_ID=$(echo "$RELEASE_JSON" | jq -r '.id')

if [[ -z "$UPLOAD_URL" || "$UPLOAD_URL" == "null" ]]; then
    echo "❌ Error: Could not find release with tag '$TAG'."
    exit 1
fi

echo "✅ Found release ID: $RELEASE_ID"
echo "✅ Upload URL: $UPLOAD_URL"

# === LIST EXISTING ASSETS ===
EXISTING_ASSETS=$(echo "$RELEASE_JSON" | jq -r '.assets[].name')

# === FIND ALL .img.gz FILES RECURSIVELY ===
echo "🔎 Searching for .img.gz files..."
mapfile -t FILES < <(find . -type f -name '*.img.gz' | sort)

if [[ ${#FILES[@]} -eq 0 ]]; then
    echo "⚠️  No .img.gz files found."
    exit 0
fi

echo "📦 Found ${#FILES[@]} files to upload."

# === UPLOAD FILES ===
for file in "${FILES[@]}"; do
    filename=$(basename "$file")
    echo "➡️  Processing: $filename"

    # Delete existing asset with the same name if found
    if echo "$EXISTING_ASSETS" | grep -qx "$filename"; then
        asset_id=$(echo "$RELEASE_JSON" | jq -r ".assets[] | select(.name==\"$filename\") | .id")
        echo "🗑️  Deleting existing asset: $filename (ID: $asset_id)"
        curl -s -X DELETE -H "Authorization: token ${GITHUB_TOKEN}" \
             "https://api.github.com/repos/${OWNER}/${REPO}/releases/assets/${asset_id}" >/dev/null
        echo "✅ Deleted old asset: $filename"
    fi

    # Upload new file
    echo "⬆️  Uploading new version: $filename"
    curl -sSL \
        -H "Authorization: token ${GITHUB_TOKEN}" \
        -H "Content-Type: application/gzip" \
        --upload-file "$file" \
        "${UPLOAD_URL}?name=${filename}" >/dev/null

    echo "✅ Uploaded: $filename"
done

echo "🎉 All uploads completed successfully!"
