#!/bin/bash
# Package pattern: "rocm-llvm-" followed by any characters and ending with ".pkg.tar.zst"
PACKAGE_PATTERN='rocm-llvm-[^"'\'' >]*\.pkg\.tar\.zst'
POOL_DIR="pool/packages"

# Iterate over each line in /etc/pacman.d/mirrorlist that starts with "Server"
grep -E '^Server' /etc/pacman.d/mirrorlist | while read -r line; do
    # Extract the base URL (the part after "=")
    base=$(echo "$line" | sed -E 's/.*=\s*(.*)/\1/')
    # Get only the protocol and domain, discarding any extra paths
    root=$(echo "$base" | sed -E 's|(https?://[^/]+).*|\1|')
    # Ensure that root ends with a "/"
    [[ "${root: -1}" != "/" ]] && root="${root}/"
    
    # URL for the packages directory
    dir_url="${root}${POOL_DIR}/"
    echo "Listing files at: $dir_url"
    
    # Retrieve the directory listing
    listing=$(curl -s "$dir_url")
    if [ -z "$listing" ]; then
        echo "Could not retrieve listing from $dir_url (possibly the mirror does not allow directory listing)"
        echo "-----------------------------"
        continue
    fi

    # Search the listing for a package name matching the pattern
    package=$(echo "$listing" | grep -oE "$PACKAGE_PATTERN" | head -n 1)
    if [ -z "$package" ]; then
        echo "No package matching the pattern was found in $dir_url"
        echo "-----------------------------"
        continue
    fi

    # Build the complete package URL
    full_url="${dir_url}${package}"
    echo "Testing: $full_url"
    
    # Download the complete package (discarding the data) and measure the download speed in bytes/s
    speed_bytes=$(curl -o /dev/null -s -w "%{speed_download}" "$full_url")
    
    # Convert the speed to MB/s (1 MB = 1048576 bytes)
    speed_MB=$(echo "scale=2; $speed_bytes/1048576" | bc)
    echo "Download speed: $speed_MB MB/s"
    echo "-----------------------------"
done

