#!/bin/sh
set -u

API_URL="${SPARKCR_API_URL:-https://sparkcr.cn/api/sparkcr.v1.QuotaService/GetNetworkStatus}"
CURL_IP_VERSION="${SPARKCR_CURL_IP_VERSION:-}"
CURL_IP_FLAG=""
USE_EMOJI=0

if [ "$#" -gt 0 ]; then
  case "$1" in
    -4|--ipv4)
      CURL_IP_VERSION="4"
      shift
      ;;
    -6|--ipv6)
      CURL_IP_VERSION="6"
      shift
      ;;
  esac
fi

if [ "$#" -gt 0 ]; then
  printf '不支持指定 IP，请使用 -4 或 -6 检测当前出口 IP。\n' >&2
  exit 2
fi

case "$CURL_IP_VERSION" in
  ""|"auto") ;;
  "4"|"IPv4"|"ipv4")
    CURL_IP_FLAG="-4"
    ;;
  "6"|"IPv6"|"ipv6")
    CURL_IP_FLAG="-6"
    ;;
  *)
    printf '无效的 SPARKCR_CURL_IP_VERSION: %s\n' "$CURL_IP_VERSION" >&2
    printf '可选值: 4, 6, auto\n' >&2
    exit 2
    ;;
esac

if [ -t 1 ] && [ "${SPARKCR_NO_EMOJI:-0}" != "1" ]; then
  case "${LC_ALL:-${LC_CTYPE:-${LANG:-}}}" in
    *UTF-8*|*utf8*|*UTF8*)
      case "${TERM:-}" in
        ""|dumb) ;;
        *) USE_EMOJI=1 ;;
      esac
      ;;
  esac
fi

BODY="{}"

JSON="$(curl -fsSL \
  $CURL_IP_FLAG \
  -X POST \
  -H "Content-Type: application/json" \
  --data "$BODY" \
  "$API_URL")" || exit 1

printf 'SparkCR 网络检测\n'
printf '=================\n'

if ! command -v jq >/dev/null 2>&1; then
  printf '未安装 jq，无法格式化输出。\n'
  printf '原始响应:\n'
  printf '%s\n' "$JSON"
  if [ "${SPARKCR_STRICT_PEERING:-0}" = "1" ]; then
    printf '%s\n' "$JSON" | grep '"isPeering"[[:space:]]*:[[:space:]]*true' >/dev/null
    exit $?
  fi
  exit 0
fi

IS_PEERING="$(printf '%s\n' "$JSON" | jq -r '.sourceGroup.isPeering // false')"
IS_AUTH="$(printf '%s\n' "$JSON" | jq -r '.isAuthenticated // false')"
IP_VALUE="$(printf '%s\n' "$JSON" | jq -r '.checkedIp // "-"')"
ASN_VALUE="$(printf '%s\n' "$JSON" | jq -r 'if (.geo.asn // 0) == 0 then "-" else "AS\(.geo.asn)" end')"
ASN_ORG="$(printf '%s\n' "$JSON" | jq -r '.geo.asnOrg // "-"')"
LOCATION="$(printf '%s\n' "$JSON" | jq -r '[.geo.country, .geo.region, .geo.city] | map(select(. != null and . != "")) | join(" / ") | if . == "" then "-" else . end')"

if [ "$IS_PEERING" = "true" ]; then
  STATUS="Peering"
else
  STATUS="非 Peering"
fi

STATUS_ICON=""
if [ "$USE_EMOJI" = "1" ]; then
  if [ "$IS_PEERING" = "true" ]; then
    STATUS_ICON="✅ "
  else
    STATUS_ICON="➖ "
  fi
fi

printf '状态:    %s%s\n' "$STATUS_ICON" "$STATUS"
printf 'IP:      %s\n' "$IP_VALUE"
printf 'ASN:     %s\n' "$ASN_VALUE"
printf 'ASN 组织: %s\n' "$ASN_ORG"
printf '位置:    %s\n' "$LOCATION"
printf '\n'

if [ "$IS_PEERING" = "true" ] && [ "$IS_AUTH" = "true" ]; then
  printf 'Peering + 已登录 — 免费不限量拉取。\n'
elif [ "$IS_PEERING" = "true" ]; then
  printf '已检测到 Peering 网络。登录后即可享受免费不限量拉取。\n'
else
  printf '此 IP 不在 Peering 网络覆盖范围内。\n'
  printf '查看覆盖范围: https://sparkcr.io/network\n'
fi

if [ "${SPARKCR_STRICT_PEERING:-0}" = "1" ]; then
  printf '%s\n' "$JSON" | jq -e '.sourceGroup.isPeering == true' >/dev/null
  exit $?
fi

exit 0
