# shellcheck shell=bash # Sourced helpers for omarchy-cn-mirror-* commands CN_MIRRORS_JSON="$OMARCHY_PATH/cn/mirrors.json" CN_MIRRORLIST="/etc/pacman.d/mirrorlist" CN_PROFILE_FILE="$HOME/.config/omarchycn/mirror-profile" cn_mirror_ids() { jq -r '.mirrors[].id' "$CN_MIRRORS_JSON" } cn_mirror_url() { jq -r --arg id "$1" '.mirrors[] | select(.id == $id) | .url' "$CN_MIRRORS_JSON" } cn_mirror_name() { jq -r --arg id "$1" '.mirrors[] | select(.id == $id) | .name' "$CN_MIRRORS_JSON" } cn_mirror_ids_by_region() { jq -r --arg r "$1" '.mirrors[] | select(.region == $r) | .id' "$CN_MIRRORS_JSON" } # Probe one mirror: prints " " cn_mirror_probe() { local url="$1" local speed ttfb lastsync age now read -r speed ttfb < <(curl -sS -o /dev/null -m 12 --connect-timeout 5 \ -w '%{speed_download} %{time_starttransfer}\n' \ "$url/core/os/x86_64/core.db" 2>/dev/null) || true speed="${speed%%.*}" [[ -z $speed ]] && speed=0 age="unknown" lastsync=$(curl -sS -m 5 --connect-timeout 5 "$url/lastsync" 2>/dev/null | tr -cd '0-9') if [[ -n $lastsync ]]; then now=$(date +%s) age=$((now - lastsync)) (( age > 86400 )) && age="stale" fi echo "$speed ${ttfb:-0} $age" } # Rank ids by probe speed, excluding dead (speed 0) and stale mirrors cn_mirror_rank() { local id url speed ttfb age for id in "$@"; do url=$(cn_mirror_url "$id") read -r speed ttfb age < <(cn_mirror_probe "$url") (( speed > 0 )) || continue [[ $age == "stale" ]] && continue echo "$speed $id" done | sort -rn | awk '{print $2}' } # Write mirrorlist from mirror ids (first = primary), with timestamped backup cn_mirror_write_list() { local profile="$1" shift local stamp id url content="" stamp=$(date +%Y%m%d-%H%M%S) content="## OmarchyCN mirrorlist (profile: $profile, generated $stamp)\n" for id in "$@"; do url=$(cn_mirror_url "$id") content+="## $id: $(cn_mirror_name "$id")\nServer = $url/\$repo/os/\$arch\n" done sudo cp "$CN_MIRRORLIST" "$CN_MIRRORLIST.omarchycn-bak-$stamp" printf '%b' "$content" | sudo tee "$CN_MIRRORLIST" > /dev/null mkdir -p "${CN_PROFILE_FILE%/*}" echo "$profile" > "$CN_PROFILE_FILE" echo "Mirrorlist written ($CN_MIRRORLIST), backup: $CN_MIRRORLIST.omarchycn-bak-$stamp" }