#!/usr/bin/env bash

MIRRORLIST="/etc/pacman.d/chaotic-mirrorlist"
TIMEOUT=6
TEST_PATH="chaotic-aur/x86_64/chaotic-aur.db"
TOP_N=5

MIRRORS=(
    "de-mirror" "cdn-mirror" "geo-mirror" "pl-mirror"
    "nl-mirror" "ch-mirror" "se-mirror" "fr-mirror"
    "gb-mirror" "de-2-mirror" "nl-1-mirror" "pl-1-mirror"
    "se-1-mirror" "ch-1-mirror"
)

tmp=$(mktemp)

echo "==> Ranking Chaotic-AUR mirrors..."

for m in "${MIRRORS[@]}"; do
    url="https://${m}.chaotic.cx/${TEST_PATH}"
    t=$(curl -o /dev/null -s -w "%{time_starttransfer}" \
        --max-time "$TIMEOUT" --connect-timeout 3 \
        -r 0-1023 "$url" 2>/dev/null)
    rc=$?
    if [ "$rc" -eq 0 ] && [[ "$t" != "0.000000" ]] && [[ -n "$t" ]]; then
        echo "${t} ${m}" >> "$tmp"
        echo "  OK   ${t}s   ${m}"
    else
        echo "  FAIL         ${m}"
    fi
done

if [ ! -s "$tmp" ]; then
    echo "==> WARNING: no mirrors responded, keeping original mirrorlist"
    rm -f "$tmp"
    exit 0
fi

sorted=$(sort -n "$tmp")
rm -f "$tmp"

cp "$MIRRORLIST" "${MIRRORLIST}.bak" 2>/dev/null || true

count=0
{
    echo "# Chaotic-AUR mirrorlist"
    echo "# Generated by chaotic-rankmirrors on $(date)"
    echo ""
    while IFS= read -r e; do
        [ "$count" -ge "$TOP_N" ] && break
        m="${e#* }"
        echo "Server = https://${m}.chaotic.cx/\$repo/\$arch"
        count=$((count + 1))
    done <<< "$sorted"
} > "$MIRRORLIST"

echo "==> Done. Updated mirrorlist with ${count} fastest mirrors."
