#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Read-only inspection; optional bounded requests to an explicitly supplied origin.
set -u
if (( $# == 1 )) && [[ ${1-} == --help ]]; then
  printf '用法: bash proxy-env-check.sh [--test https://example.com]\n默认只查看代理变量是否存在，不显示值、不发请求。\n'
  exit 0
fi
origin=''
if (( $# )); then
  if (( $# != 2 )) || [[ $1 != --test ]] ||
    [[ ! $2 =~ ^https?://[a-zA-Z0-9.-]+(:[0-9]{1,5})?/?$ ]]; then
    printf '请输入 --test 和不含账号、路径、查询参数的 http(s) 网站根地址。\n' >&2
    exit 2
  fi
  origin=$2
fi
printf '代理环境变量（仅当前进程继承的值；内容已隐藏）\n'
for name in http_proxy https_proxy all_proxy no_proxy HTTP_PROXY HTTPS_PROXY ALL_PROXY NO_PROXY; do
  if [[ ! -v $name ]]; then
    printf '%s: 未设置\n' "$name"
  elif [[ -z ${!name} ]]; then
    printf '%s: 空值\n' "$name"
  else
    printf '%s: 已设置（不显示地址或凭据）\n' "$name"
  fi
done
printf '这不代表桌面、Git、容器或后台服务的全部代理设置。curl 不采用大写 HTTP_PROXY。\n'
[[ -n $origin ]] || exit 0
if ! command -v curl >/dev/null 2>&1; then
  printf '缺少 curl：先运行不带 --test 的检查，再按系统软件管理方式准备 curl。\n' >&2
  exit 3
fi
# --disable must be first, so local curlrc cannot add credentials or other requests.
normal_code=$(curl --disable --silent --head --output /dev/null --write-out '%{http_code}' \
  --connect-timeout 3 --max-time 8 --proto '=http,https' --url "$origin" 2>/dev/null)
normal_exit=$?
direct_code=$(curl --disable --silent --head --output /dev/null --write-out '%{http_code}' \
  --connect-timeout 3 --max-time 8 --proto '=http,https' --noproxy '*' --url "$origin" 2>/dev/null)
direct_exit=$?
printf '继承代理变量: curl退出码=%s HTTP=%s\n' "$normal_exit" "$normal_code"
printf '本次绕过代理: curl退出码=%s HTTP=%s\n' "$direct_exit" "$direct_code"
if (( normal_exit != 0 && direct_exit == 0 )); then
  printf '直连有响应、原方式失败：先核对代理变量和代理服务，再按教程做单次取消代理的对照。\n'
elif (( normal_exit == 0 && direct_exit != 0 )); then
  printf '原方式有响应、直连失败：当前网络可能需要代理；不要直接删除原配置。\n'
elif (( normal_exit == 0 && direct_exit == 0 )); then
  printf '两种方式都有 HTTP 响应。状态码不等于登录成功，也不证明所有网站可用。\n'
else
  printf '两种方式都失败：按退出码区分解析、连接、超时和证书问题，不要直接认定代理是唯一原因。\n'
fi
printf '本次只发送 HEAD，不跟随跳转、不改配置；网站可能不支持 HEAD。\n'
(( normal_exit == 0 || direct_exit == 0 ))
