#!/bin/bash
# omarchy:summary=Apply a mirror profile or pin one mirror for pacman
# omarchy:args=<china|official|mirror-id>
# omarchy:examples=omarchycn mirror apply china | omarchycn mirror apply official | omarchycn mirror apply tuna
# omarchy:requires-sudo=true

set -euo pipefail

source "$OMARCHY_PATH/cn/lib/mirror.sh"

target="${1:?usage: omarchycn mirror apply <china|official|mirror-id>}"

case "$target" in
china)
  echo "Benchmarking China mirrors..."
  mapfile -t cn_ids < <(cn_mirror_ids_by_region cn)
  mapfile -t ranked < <(cn_mirror_rank "${cn_ids[@]}")
  if (( ${#ranked[@]} == 0 )); then
    echo "No healthy China mirror reachable; keeping current mirrorlist" >&2
    exit 1
  fi
  # Primary + up to two backups
  cn_mirror_write_list china "${ranked[@]:0:3}"
  ;;
official)
  cn_mirror_write_list official geo worldwide
  ;;
*)
  url=$(cn_mirror_url "$target")
  if [[ -z $url ]]; then
    echo "Unknown mirror id: $target (see: omarchycn mirror benchmark)" >&2
    exit 1
  fi
  cn_mirror_write_list "pin:$target" "$target"
  ;;
esac
