#!/usr/bin/env bash
# 部署脚本共用：读取 HTTP_PROXY / http_proxy 并配置 apt、git、pip、curl
# 用法（install.sh / update.sh 前）：
#   export http_proxy=http://192.168.8.246:10810
#   export https_proxy=http://192.168.8.246:10810
#   export HTTP_PROXY="$http_proxy"
#   export HTTPS_PROXY="$https_proxy"
#
# pip 镜像（可覆盖）：
#   export PIP_MIRROR=https://mirrors.aliyun.com/pypi/simple

# 国内镜像优先；代理不可用时仍可走直连镜像。官方源放最后。
PIP_MIRROR_FALLBACKS=(
  "https://pypi.tuna.tsinghua.edu.cn/simple"
  "https://mirrors.aliyun.com/pypi/simple"
  "https://mirrors.cloud.tencent.com/pypi/simple"
  "https://pypi.org/simple"
)

setup_deploy_proxy() {
  local proxy="${HTTP_PROXY:-${http_proxy:-}}"
  if [[ -z "$proxy" ]]; then
    return 0
  fi

  if [[ "$proxy" != http://* && "$proxy" != https://* && "$proxy" != socks5://* ]]; then
    proxy="http://${proxy}"
  fi

  export http_proxy="$proxy"
  export https_proxy="${HTTPS_PROXY:-${https_proxy:-$proxy}}"
  export HTTP_PROXY="$http_proxy"
  export HTTPS_PROXY="$https_proxy"
  export ALL_PROXY="${ALL_PROXY:-$http_proxy}"

  # 国内 PyPI 镜像走直连，避免坏代理导致 "from versions: none"
  local no_proxy_extra="pypi.tuna.tsinghua.edu.cn,mirrors.aliyun.com,mirrors.cloud.tencent.com,files.pythonhosted.org"
  if [[ -z "${NO_PROXY:-${no_proxy:-}}" ]]; then
    export NO_PROXY="127.0.0.1,localhost,${no_proxy_extra}"
    export no_proxy="${NO_PROXY}"
  else
    export NO_PROXY="${NO_PROXY:-${no_proxy}},${no_proxy_extra}"
    export no_proxy="${NO_PROXY}"
  fi

  if declare -F log_info >/dev/null 2>&1; then
    log_info "使用网络代理: ${http_proxy}"
  else
    echo "[INFO] 使用网络代理: ${http_proxy}"
  fi

  mkdir -p /etc/apt/apt.conf.d
  cat > /etc/apt/apt.conf.d/95grade-archive-proxy <<EOF
Acquire::http::Proxy "${http_proxy}";
Acquire::https::Proxy "${https_proxy}";
EOF
}

pip_host_from_url() {
  # https://host/path -> host
  local url="$1"
  url="${url#https://}"
  url="${url#http://}"
  echo "${url%%/*}"
}

# 用法: pip_install_with_fallback --upgrade pip
#       pip_install_with_fallback -r requirements.txt
# 依次尝试 PIP_MIRROR 与备用镜像；失败时给出代理提示。
pip_install_with_fallback() {
  local mirrors=()
  local m seen=""
  if [[ -n "${PIP_MIRROR:-}" ]]; then
    mirrors+=("${PIP_MIRROR}")
  fi
  for m in "${PIP_MIRROR_FALLBACKS[@]}"; do
    mirrors+=("$m")
  done

  local mirror host
  for mirror in "${mirrors[@]}"; do
    case " ${seen} " in
      *" ${mirror} "*) continue ;;
    esac
    seen="${seen} ${mirror}"

    host="$(pip_host_from_url "${mirror}")"
    if declare -F log_info >/dev/null 2>&1; then
      log_info "pip 安装（镜像: ${mirror}）…"
    else
      echo "[INFO] pip 安装（镜像: ${mirror}）…"
    fi

    if pip install "$@" --progress-bar on -i "${mirror}" --trusted-host "${host}"; then
      return 0
    fi
    if declare -F log_warn >/dev/null 2>&1; then
      log_warn "镜像不可用: ${mirror}，尝试下一个…"
    else
      echo "[WARN] 镜像不可用: ${mirror}，尝试下一个…"
    fi
  done

  if declare -F log_error >/dev/null 2>&1; then
    log_error "所有 pip 镜像均失败（常见原因：服务器无法访问外网 / 代理未设置 / 代理拦截 HTTPS）。"
    log_error "请先检测网络，再重试安装："
    log_error "  curl -I https://pypi.tuna.tsinghua.edu.cn/simple/fastapi/"
    log_error "  export http_proxy=http://192.168.8.246:10810"
    log_error "  export https_proxy=\$http_proxy HTTP_PROXY=\$http_proxy HTTPS_PROXY=\$http_proxy"
    log_error "  # 或换镜像: export PIP_MIRROR=https://mirrors.aliyun.com/pypi/simple"
  else
    echo "[ERROR] 所有 pip 镜像均失败。请设置代理或更换 PIP_MIRROR 后重试。" >&2
  fi
  return 1
}
