#!/bin/bash

# Find Latest Build Script
# This script helps find the latest successful build and provides download links

set -e

echo "=== Finding Latest libostree-dev Build ==="
echo ""

# Try to get the latest successful build from the repository
REPO_URL="https://git.raines.xyz/robojerk/libostree-dev"

echo "Repository: $REPO_URL"
echo ""

# Check if we can access the actions page
echo "Checking available builds..."
echo ""

# Try different possible workflow run URLs
POSSIBLE_RUNS=(97 98 99 100 101 102)

for run_id in "${POSSIBLE_RUNS[@]}"; do
    echo "Checking build #$run_id..."
    if curl -s -o /dev/null -w "%{http_code}" "$REPO_URL/actions/runs/$run_id" | grep -q "200"; then
        echo "✅ Found working build: #$run_id"
        WORKING_RUN_ID=$run_id
        break
    else
        echo "❌ Build #$run_id not found"
    fi
done

if [ -z "$WORKING_RUN_ID" ]; then
    echo ""
    echo "❌ Could not find a working build automatically."
    echo ""
    echo "Please manually check the Actions tab:"
    echo "$REPO_URL/actions"
    echo ""
    echo "Look for the most recent successful 'Build libostree Backport' run."
    exit 1
fi

echo ""
echo "=== Latest Working Build Found ==="
echo "Build ID: $WORKING_RUN_ID"
echo "URL: $REPO_URL/actions/runs/$WORKING_RUN_ID"
echo ""

echo "To download packages:"
echo "1. Visit: $REPO_URL/actions/runs/$WORKING_RUN_ID"
echo "2. Look for 'Artifacts' section"
echo "3. Download 'release-assets'"
echo "4. Extract the archive"
echo ""

echo "Available packages (after extraction):"
echo "- libostree-dev_2025.2-1~noble1_amd64.deb"
echo "- libostree-dev-dbgsym_2025.2-1~noble1_amd64.ddeb"
echo ""

echo "Installation:"
echo "sudo dpkg -i libostree-dev_2025.2-1~noble1_amd64.deb"
echo "sudo apt-get install -f"
echo ""

echo "Opening build page..."
if command -v xdg-open >/dev/null 2>&1; then
    xdg-open "$REPO_URL/actions/runs/$WORKING_RUN_ID"
elif command -v open >/dev/null 2>&1; then
    open "$REPO_URL/actions/runs/$WORKING_RUN_ID"
else
    echo "Please visit: $REPO_URL/actions/runs/$WORKING_RUN_ID"
fi 