#!/usr/bin/env bash

SUBSTITUTERS=(
  "https://cache.garnix.io"
  "https://cache.m7.rs"
  "https://cache.nixos.org"
  "https://cache.soopy.moe"
  "https://chaotic-nyx.cachix.org"
  "https://colmena.cachix.org"
  "https://hyprland.cachix.org"
  "https://mirrors.tuna.tsinghua.edu.cn/nix-channels/store"
  "https://mirrors.ustc.edu.cn/nix-channels/store"
  "https://nix-community.cachix.org"
  "https://nix-gaming.cachix.org"
  "https://nixos-cache-proxy.cofob.dev"
  "https://nixos.snix.store"
  "https://nixos.tvix.store"
)

TEST_HASH="sha256-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="

clean_url() {
  echo "$1" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//'
}

check_speed() {
  local url=$(clean_url "$1")
  local cache_info=$(curl -s -o /dev/null -w "%{http_code},%{time_total}" -L "${url}/nix-cache-info" --max-time 10 --insecure)
  IFS=',' read -r code time_info <<< "$cache_info"
  
  if [[ "$code" == "200" ]]; then
    echo -e "\033[1;32m✓ nix-cache-info: ${time_info}s\033[0m"
    
    local narinfo_time=$(curl -s -o /dev/null -w "%{time_total}" -L "${url}/${TEST_HASH}.narinfo" --max-time 10 --insecure)
    echo -e "  .narinfo: \033[1;33m${narinfo_time}s\033[0m"
    
    local nar_time=$(curl -s -o /dev/null -w "%{time_total}" -L "${url}/nar/${TEST_HASH}.nar.xz" --max-time 10 --insecure)
    echo -e "  .nar.xz:   \033[1;33m${nar_time}s\033[0m"
    
    local speed=$(curl -s -o /dev/null -w "%{speed_download}" -L "${url}/nix-cache-info" --max-time 10 --insecure)
    echo -e "  СКОРОСТЬ: \033[1;36m$(numfmt --to=iec-i --suffix=B/s $speed | sed 's/Bi *//')\033[0m"
    return 0
  else
    echo -e "\033[1;31m✗ nix-cache-info: $code (${time_info}s)\033[0m"
    return 1
  fi
}

main() {
  echo "🚀 Тест скорости Nix Substituters ($(date '+%H:%M:%S'))"
  echo "=============================================="
  
  local working=()
  
  for url in "${SUBSTITUTERS[@]}"; do
    local clean_url=$(clean_url "$url")
    echo -e "\n\033[1;34m=== $clean_url ===\033[0m"
    
    if check_speed "$url"; then
      working+=("$clean_url")
    fi
    echo "----------------------------------------"
  done
  
  echo -e "\n\033[1;36m🏆 РЕКОМЕНДУЕМЫЙ ПОРЯДОК (по скорости):\033[0m"
  printf 'nix.settings.substituters = [\n'
  for url in "${working[@]}"; do
    printf '  "%s"\n' "$url"
  done
  printf '];\n'
}

main
