#!/usr/bin/env bash

set -e

URL="https://mirrors.aliyun.com/pypi/simple/hezor-common/"
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
PROJECT_DIR="$(dirname "$SCRIPT_DIR")"
BUMP_FILE="$PROJECT_DIR/.bumpversion.toml"

get_latest_version() {
  curl -s "$URL" \
  | grep -oE 'hezor[_-]common-[0-9]+\.[0-9]+\.[0-9]+' \
  | sed -E 's/hezor[_-]common-//' \
  | sort -uV \
  | tail -n1
}

get_local_version() {
  grep -E '^current_version' "$BUMP_FILE" \
  | sed -E 's/.*"(.*)"/\1/'
}

while true; do
  MIRROR_VERSION=$(get_latest_version || true)
  LOCAL_VERSION=$(get_local_version || true)

  NOW=$(date "+%Y-%m-%d %H:%M:%S")

  if [[ -z "$MIRROR_VERSION" ]]; then
    echo "$NOW ❌ 获取镜像版本失败"
  else
    if [[ "$MIRROR_VERSION" == "$LOCAL_VERSION" ]]; then
      echo "$NOW ✅ 已同步 mirror=$MIRROR_VERSION local=$LOCAL_VERSION"
      exit 0
    else
      echo "$NOW ⏳ 未同步 mirror=$MIRROR_VERSION local=$LOCAL_VERSION"
    fi
  fi

  sleep 60
done