#!/usr/bin/env bash
# nginx.cc/fix — served payload. Common library first, then the script body.
# Verify: curl -fsSL https://nginx.cc/fix.sh | sha256sum  (compare with https://nginx.cc/fix.sh.sha256)
{
# =============================================================================
# nginx.cc common library (same conventions as xyz.sh/lib/common.sh)
# Unofficial community tooling. Not affiliated with F5, Inc. or the NGINX project.
#
# Promises:
#   - No telemetry, analytics, or background "phone-home" calls
#   - Official upstream URLs (nginx.org) are printed before they are used
#   - Every system-changing step is announced; --dry-run changes nothing
#   - Changes need confirmation (TTY) or -y / YES=1
# =============================================================================

# shellcheck disable=SC2034  # variables are consumed by the scripts that source this file
if [[ -n "${NCC_COMMON_LOADED:-}" ]]; then
  # shellcheck disable=SC2317
  return 0 2>/dev/null || true
fi
NCC_COMMON_LOADED=1

set -euo pipefail

NCC_VERSION="0.1.0"
NCC_BASE="${NCC_BASE:-https://nginx.cc}"
NCC_NAME="${NCC_NAME:-unknown}"

if [[ -z "${NCC_LANG:-}" ]]; then
  case "${LC_ALL:-${LC_MESSAGES:-${LANG:-}}}" in
    zh*|ZH*|cmn*) NCC_LANG="zh" ;;
    *) NCC_LANG="en" ;;
  esac
fi

ncc_t() { if [[ "${NCC_LANG}" == "zh" ]]; then printf '%s' "${2:-$1}"; else printf '%s' "$1"; fi; }

_ncc_color=0
case "${NCC_COLOR:-auto}" in
  always) _ncc_color=1 ;;
  never) _ncc_color=0 ;;
  *) [[ -t 1 && -z "${NO_COLOR:-}" ]] && _ncc_color=1 ;;
esac
if [[ "${_ncc_color}" == "1" ]]; then
  C_RESET=$'\033[0m'; C_BOLD=$'\033[1m'; C_DIM=$'\033[2m'
  C_RED=$'\033[31m'; C_GREEN=$'\033[32m'; C_YELLOW=$'\033[33m'; C_CYAN=$'\033[36m'
else
  C_RESET=""; C_BOLD=""; C_DIM=""; C_RED=""; C_GREEN=""; C_YELLOW=""; C_CYAN=""
fi

ncc_info()  { printf '%s[INFO]%s %s\n'  "${C_GREEN}"  "${C_RESET}" "$*"; }
ncc_warn()  { printf '%s[WARN]%s %s\n'  "${C_YELLOW}" "${C_RESET}" "$*" >&2; }
ncc_error() { printf '%s[ERROR]%s %s\n' "${C_RED}"    "${C_RESET}" "$*" >&2; }
ncc_step()  { printf '%s==>%s %s\n'     "${C_CYAN}"   "${C_RESET}" "$*"; }
ncc_ok()    { printf '%s[ OK ]%s %s\n'  "${C_GREEN}"  "${C_RESET}" "$*"; }
ncc_tip()   { printf '%s[TIP ]%s %s\n'  "${C_CYAN}"   "${C_RESET}" "$*"; }

NCC_ARGS=()
NCC_YES=0
NCC_DRY_RUN=0
NCC_HELP=0

ncc_parse_global_args() {
  local filtered=() arg
  for arg in "$@"; do
    case "${arg}" in
      -y|--yes) NCC_YES=1 ;;
      --lang=zh|zh) NCC_LANG="zh" ;;
      --lang=en|en) NCC_LANG="en" ;;
      --dry-run) NCC_DRY_RUN=1 ;;
      --no-color) C_RESET=""; C_BOLD=""; C_DIM=""; C_RED=""; C_GREEN=""; C_YELLOW=""; C_CYAN="" ;;
      -h|--help) NCC_HELP=1 ;;
      *) filtered+=("${arg}") ;;
    esac
  done
  NCC_ARGS=("${filtered[@]+"${filtered[@]}"}")
  if [[ "${YES:-}" =~ ^(1|yes|true|YES)$ ]]; then NCC_YES=1; fi
}

ncc_banner() {
  printf '\n%s%snginx.cc/%s%s  v%s\n' "${C_BOLD}" "${C_CYAN}" "${NCC_NAME}" "${C_RESET}" "${NCC_VERSION}"
  printf '%s\n' "${C_DIM}----------------------------------------${C_RESET}"
  printf '  %s: %s/%s.sh   sha256: %s/%s.sh.sha256\n' "$(ncc_t "Source" "源码")" "${NCC_BASE}" "${NCC_NAME}" "${NCC_BASE}" "${NCC_NAME}"
  printf '  %s\n' "$(ncc_t "Unofficial tool, not affiliated with F5/NGINX. No telemetry." "非官方工具，与 F5/NGINX 无关联。无遥测。")"
  [[ "${NCC_DRY_RUN}" == "1" ]] && printf '  %s%s%s\n' "${C_YELLOW}" "$(ncc_t "DRY RUN: nothing will be changed." "演练模式（--dry-run）：不会做任何修改。")" "${C_RESET}"
  printf '%s\n\n' "${C_DIM}----------------------------------------${C_RESET}"
}

ncc_is_root() { [[ "${EUID:-$(id -u)}" -eq 0 ]]; }
ncc_need_cmd() { command -v "$1" >/dev/null 2>&1; }

# shellcheck disable=SC2034 # library globals; not every script reads all of them
NCC_OS_ID=""; NCC_OS_LIKE=""; NCC_OS_VERSION=""; NCC_OS_CODENAME=""; NCC_OS_FAMILY="unknown"; NCC_OS_PRETTY="unknown"
# shellcheck disable=SC2034 # library globals; not every script reads all of them
ncc_detect_os() {
  if [[ -r /etc/os-release ]]; then
    # shellcheck disable=SC1091
    . /etc/os-release
    NCC_OS_ID="${ID:-}"; NCC_OS_LIKE="${ID_LIKE:-}"; NCC_OS_VERSION="${VERSION_ID:-}"
    NCC_OS_CODENAME="${VERSION_CODENAME:-${UBUNTU_CODENAME:-}}"; NCC_OS_PRETTY="${PRETTY_NAME:-$NCC_OS_ID}"
  fi
  case " ${NCC_OS_ID} ${NCC_OS_LIKE} " in
    *" debian "*|*" ubuntu "*) NCC_OS_FAMILY="debian" ;;
    *rhel*|*centos*|*fedora*|*rocky*|*alma*) NCC_OS_FAMILY="rhel" ;;
    *) NCC_OS_FAMILY="unknown" ;;
  esac
}

ncc_init() {
  ncc_parse_global_args "$@"
  ncc_detect_os
  ncc_banner
}

# Run a system-changing command, or just print it under --dry-run.
ncc_run() {
  if [[ "${NCC_DRY_RUN}" == "1" ]]; then
    printf '%s[dry-run]%s %s\n' "${C_DIM}" "${C_RESET}" "$*"
    return 0
  fi
  printf '%s+%s %s\n' "${C_DIM}" "${C_RESET}" "$*"
  "$@"
}

# Write stdin to a file (or print it under --dry-run).
ncc_write_file() {
  local path="$1" content
  content="$(cat)"
  if [[ "${NCC_DRY_RUN}" == "1" ]]; then
    printf '%s[dry-run]%s write %s:\n%s\n' "${C_DIM}" "${C_RESET}" "${path}" "$(printf '%s\n' "${content}" | sed 's/^/    | /')"
    return 0
  fi
  printf '%s\n' "${content}" > "${path}"
  printf '%s+%s wrote %s\n' "${C_DIM}" "${C_RESET}" "${path}"
}


ncc_confirm() {
  local prompt="$1" reply="" fd
  if [[ "${NCC_DRY_RUN}" == "1" ]]; then return 0; fi
  if [[ "${NCC_YES}" == "1" ]]; then
    ncc_info "$(ncc_t "Auto-confirmed (-y):" "已自动确认（-y）：") ${prompt}"; return 0
  fi
  if { exec {fd}<>/dev/tty; } 2>/dev/null && [[ -t "${fd}" ]]; then
    printf '%s [y/N] ' "${prompt}" >&"${fd}"
    read -r reply <&"${fd}" || true
    exec {fd}>&- 2>/dev/null || true
  else
    ncc_warn "$(ncc_t "No TTY for confirmation. Re-run with -y if you accept." "没有可用终端确认。确认无误请加 -y 重新运行。")"
    return 1
  fi
  [[ "${reply}" =~ ^(y|Y|yes|YES)$ ]]
}

ncc_has_systemd() { [[ -d /run/systemd/system ]] && ncc_need_cmd systemctl; }

ncc_backup_file() {
  local f="$1" bak
  bak="${f}.ncc-bak-$(date +%Y%m%d%H%M%S)"
  if [[ -e "${f}" ]]; then
    if [[ "${NCC_DRY_RUN}" == "1" ]]; then printf '%s' "${bak}"; return 0; fi
    cp -a "${f}" "${bak}"; printf '%s' "${bak}"
  fi
}

# ---- nginx.cc/fix body ----
# nginx.cc/fix — read-only nginx health check with suggestions.
#
# Usage:
#   curl -fsSL nginx.cc/fix | bash                      # read-only check (default)
#   curl -fsSL nginx.cc/fix | sudo bash                 # as root: also runs nginx -t / reads certs
#   curl -fsSL nginx.cc/fix | sudo bash -s -- --apply-hardening   # opt-in change, see below
#
# Default mode NEVER changes anything. The only change this script can make is
# --apply-hardening: write /etc/nginx/conf.d/00-nginxcc-hardening.conf with
# "server_tokens off;", validate with nginx -t, reload, and roll back on failure.
# Unofficial script, not affiliated with F5/NGINX. No telemetry.

set -euo pipefail

if [[ -z "${NCC_COMMON_LOADED:-}" ]]; then
  _ncc_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
  # shellcheck source=lib/common.sh
  source "${_ncc_dir}/lib/common.sh"
fi

# shellcheck disable=SC2034  # read by ncc_banner in lib/common.sh
NCC_NAME="fix"
ncc_init "$@"

APPLY_HARDENING=0
LOG_LINES=300
for a in "${NCC_ARGS[@]+"${NCC_ARGS[@]}"}"; do
  case "${a}" in
    --apply-hardening) APPLY_HARDENING=1 ;;
    --log-lines=*) LOG_LINES="${a#*=}" ;;
    *) ncc_warn "$(ncc_t "Unknown option ignored:" "忽略未知参数：") ${a}" ;;
  esac
done

if [[ "${NCC_HELP}" == "1" ]]; then
  cat <<HELP
$(ncc_t "Read-only nginx health check. Prints problems and suggested fixes." "只读的 nginx 体检，列出问题和修复建议。")
  --apply-hardening   $(ncc_t "opt-in: add server_tokens off via conf.d (tested, auto-rollback)" "可选：通过 conf.d 加 server_tokens off（先测试，失败自动回滚）")
  --log-lines=N       $(ncc_t "error-log lines to scan (default 300)" "扫描错误日志的行数（默认 300）")
  --dry-run           $(ncc_t "with --apply-hardening: show the change only" "配合 --apply-hardening：只显示改动")
HELP
  exit 0
fi

ISSUES=0; WARNS=0
issue() { ISSUES=$((ISSUES+1)); ncc_error "$1"; [[ -n "${2:-}" ]] && ncc_tip "$2"; return 0; }
warnx() { WARNS=$((WARNS+1)); ncc_warn "$1"; [[ -n "${2:-}" ]] && ncc_tip "$2"; return 0; }
doc() { printf '%s/%s/errors/%s' "${NCC_BASE}" "${NCC_LANG}" "$1"; }

ncc_info "$(ncc_t "Mode: read-only (nothing will be changed)" "模式：只读（不会修改任何东西）")"
ncc_is_root || ncc_warn "$(ncc_t "Not root: nginx -t, certificate and log checks may be incomplete." "非 root：nginx -t、证书和日志检查可能不完整。")"

# 1. binary ---------------------------------------------------------------
ncc_step "$(ncc_t "nginx binary" "nginx 程序")"
if ! ncc_need_cmd nginx; then
  issue "$(ncc_t "nginx is not installed (or not in PATH)." "未安装 nginx（或不在 PATH 中）。")" "curl -fsSL ${NCC_BASE}/install | sudo bash"
  printf '\n%s: %s %s, %s %s\n' "$(ncc_t "Summary" "汇总")" "${ISSUES}" "$(ncc_t "problem(s)" "个问题")" "${WARNS}" "$(ncc_t "warning(s)" "个提醒")"
  exit 0
fi
VERSION="$(nginx -v 2>&1 | sed -n 's|.*nginx/||p')"
VFLAGS="$(nginx -V 2>&1 || true)"
ncc_ok "nginx ${VERSION}"
grep -q -- "--with-http_ssl_module" <<<"${VFLAGS}" || warnx "$(ncc_t "Built without http_ssl_module (no HTTPS)." "未编译 http_ssl_module（不支持 HTTPS）。")"
grep -q -- "--with-http_v2_module" <<<"${VFLAGS}" || warnx "$(ncc_t "Built without http_v2_module." "未编译 http_v2_module。")"
if grep -q -- "--with-http_v3_module" <<<"${VFLAGS}"; then ncc_ok "$(ncc_t "HTTP/3 module available" "支持 HTTP/3 模块")"; fi
major_minor="$(printf '%s' "${VERSION}" | awk -F. '{printf "%d%03d", $1, $2}')"
if [[ -n "${major_minor}" && "${major_minor}" -lt 1022 ]]; then
  warnx "$(ncc_t "nginx ${VERSION} is old (security fixes only land in current stable/mainline)." "nginx ${VERSION} 版本较旧（安全修复只进当前 stable/mainline）。")" "curl -fsSL ${NCC_BASE}/install | sudo bash"
fi

# 2. nginx -t -------------------------------------------------------------
ncc_step "nginx -t"
TEST_OUT="$(nginx -t 2>&1 || true)"
if grep -q "test is successful" <<<"${TEST_OUT}"; then
  ncc_ok "$(ncc_t "Configuration test passed" "配置语法检查通过")"
else
  issue "$(ncc_t "nginx -t failed:" "nginx -t 失败：")"
  printf '%s\n' "${TEST_OUT}" | sed 's/^/    /'
  grep -q "Address already in use" <<<"${TEST_OUT}" && ncc_tip "$(doc address-already-in-use)"
  grep -q "Permission denied" <<<"${TEST_OUT}" && ncc_tip "$(doc permission-denied)"
fi

CONF="$(nginx -T 2>/dev/null || true)"
# Strip comments for directive checks.
CONF_NC="$(printf '%s\n' "${CONF}" | sed -e 's/#.*$//')"

# 3. service + ports ------------------------------------------------------
ncc_step "$(ncc_t "Service and ports" "服务与端口")"
if ncc_has_systemd; then
  state="$(systemctl is-active nginx 2>/dev/null || true)"
  if [[ "${state}" == "active" ]]; then ncc_ok "systemctl: active"; else issue "systemctl is-active nginx: ${state:-unknown}" "journalctl -u nginx -n 50 --no-pager"; fi
else
  ncc_info "$(ncc_t "No systemd; skipped service state." "无 systemd，跳过服务状态。")"
fi
if ncc_need_cmd ss; then
  for port in 80 443; do
    owner="$(ss -Hltnp "sport = :${port}" 2>/dev/null | sed -n 's/.*users:(("\([^"]*\)".*/\1/p' | sort -u | tr '\n' ' ')"
    if [[ -z "${owner// /}" ]]; then
      ncc_info "$(ncc_t "Port ${port}: nothing listening" "端口 ${port}：无程序监听")"
    elif [[ "${owner}" == *nginx* ]]; then
      ncc_ok "$(ncc_t "Port ${port}: nginx" "端口 ${port}：nginx")"
    else
      warnx "$(ncc_t "Port ${port} is held by: ${owner}" "端口 ${port} 被占用：${owner}")" "$(doc address-already-in-use)"
    fi
  done
fi

# 4. config review --------------------------------------------------------
if [[ -n "${CONF_NC}" ]]; then
  ncc_step "$(ncc_t "Config review (nginx -T)" "配置检查（nginx -T）")"
  if ! grep -Eq '^\s*server_tokens\s+off\s*;' <<<"${CONF_NC}"; then
    warnx "$(ncc_t "server_tokens is not off: the version number is exposed in headers and error pages." "server_tokens 未关闭：版本号会出现在响应头和错误页。")" "$(ncc_t "Add in http {}: server_tokens off;   (or re-run with --apply-hardening)" "在 http {} 中加：server_tokens off;（或用 --apply-hardening）")"
  else ncc_ok "server_tokens off"; fi
  if grep -Eq '^\s*ssl_protocols[^;]*(SSLv[23]|TLSv1(\s|;)|TLSv1\.1)' <<<"${CONF_NC}"; then
    issue "$(ncc_t "ssl_protocols allows SSLv3/TLSv1.0/TLSv1.1." "ssl_protocols 允许了 SSLv3/TLSv1.0/TLSv1.1。")" "ssl_protocols TLSv1.2 TLSv1.3;"
  fi
  if grep -Eq '^\s*ssl\s+on\s*;' <<<"${CONF_NC}"; then
    warnx "$(ncc_t "'ssl on;' is obsolete (removed in 1.25.1)." "'ssl on;' 已废弃（1.25.1 起移除）。")" "listen 443 ssl;"
  fi
  if grep -Eq '^\s*autoindex\s+on\s*;' <<<"${CONF_NC}"; then
    warnx "$(ncc_t "autoindex on: directory listings are public." "autoindex on：目录列表对外可见。")"
  fi
  if grep -Eq '^\s*listen\s+[^;]*443[^;]*ssl' <<<"${CONF_NC}" && ! grep -Eq '(^\s*http2\s+on\s*;|listen[^;]*\shttp2)' <<<"${CONF_NC}"; then
    warnx "$(ncc_t "HTTPS without HTTP/2." "HTTPS 未启用 HTTP/2。")" "$(ncc_t "nginx >= 1.25.1: http2 on;   older: listen 443 ssl http2;" "nginx ≥ 1.25.1：http2 on;  旧版本：listen 443 ssl http2;")"
  fi
  if ! grep -Eq '^\s*client_max_body_size' <<<"${CONF_NC}"; then
    ncc_info "$(ncc_t "client_max_body_size not set (default 1m). Uploads over 1 MB get 413." "未设置 client_max_body_size（默认 1m），超过 1MB 的上传会报 413。")"
  fi
  pp="$(grep -Ec '^\s*proxy_pass\s' <<<"${CONF_NC}" || true)"
  ph="$(grep -Eic '^\s*proxy_set_header\s+Host\s' <<<"${CONF_NC}" || true)"
  if [[ "${pp:-0}" -gt 0 && "${ph:-0}" -eq 0 ]]; then
    warnx "$(ncc_t "proxy_pass is used but no proxy_set_header Host is set; the backend sees the upstream name." "使用了 proxy_pass 却没有设置 proxy_set_header Host，后端收到的是 upstream 名字。")" "proxy_set_header Host \$host;"
  fi
  wc_val="$(sed -n 's/^\s*worker_connections\s\+\([0-9]\+\).*/\1/p' <<<"${CONF_NC}" | head -1)"
  if [[ -n "${wc_val}" && "${wc_val}" -lt 1024 ]]; then
    warnx "worker_connections ${wc_val} $(ncc_t "is low for a proxy." "对反向代理偏低。")" "worker_connections 4096;"
  fi

  # 5. certificates --------------------------------------------------------
  certs="$(sed -n 's/^\s*ssl_certificate\s\+\([^;]*\);.*/\1/p' <<<"${CONF_NC}" | sort -u)"
  if [[ -n "${certs}" ]] && ncc_need_cmd openssl; then
    ncc_step "$(ncc_t "Certificates" "证书")"
    while IFS= read -r c; do
      [[ -z "${c}" || "${c}" == *'$'* ]] && continue
      if [[ ! -r "${c}" ]]; then warnx "$(ncc_t "Cannot read" "无法读取") ${c}"; continue; fi
      end="$(openssl x509 -enddate -noout -in "${c}" 2>/dev/null | cut -d= -f2)"
      if ! openssl x509 -checkend 0 -noout -in "${c}" >/dev/null 2>&1; then
        issue "${c}: $(ncc_t "EXPIRED" "已过期") (${end})" "https://ssl.sh"
      elif ! openssl x509 -checkend 1209600 -noout -in "${c}" >/dev/null 2>&1; then
        warnx "${c}: $(ncc_t "expires within 14 days" "14 天内过期") (${end})" "https://ssl.sh"
      else
        ncc_ok "${c}: ${end}"
      fi
    done <<<"${certs}"
  fi
fi

# 6. error log ------------------------------------------------------------
ncc_step "$(ncc_t "Recent error log" "最近错误日志")"
ERRLOG="$(sed -n 's/^\s*error_log\s\+\([^ ;]*\).*/\1/p' <<<"${CONF_NC:-}" | grep '^/' | head -1)"
ERRLOG="${ERRLOG:-/var/log/nginx/error.log}"
if [[ -r "${ERRLOG}" ]]; then
  recent="$(tail -n "${LOG_LINES}" "${ERRLOG}" 2>/dev/null || true)"
  scan() { # pattern slug label
    local n; n="$(grep -Eic "$1" <<<"${recent}" || true)"
    if [[ "${n:-0}" -gt 0 ]]; then warnx "$3: ${n} $(ncc_t "line(s)" "行")" "$(doc "$2")"; fi
  }
  scan 'connect\(\) failed|no live upstreams|Connection refused' 502-bad-gateway "$(ncc_t "Upstream connect failures (502)" "连接上游失败（502）")"
  scan 'upstream timed out' 504-gateway-timeout "$(ncc_t "Upstream timeouts (504)" "上游超时（504）")"
  scan 'client intended to send too large body' 413-request-entity-too-large "$(ncc_t "Body too large (413)" "请求体过大（413）")"
  scan 'upstream prematurely closed' upstream-prematurely-closed "upstream prematurely closed"
  scan '\(13: Permission denied\)' permission-denied "$(ncc_t "Permission denied (13)" "权限被拒绝（13）")"
  scan 'directory index of .* is forbidden' 403-forbidden "$(ncc_t "Directory index forbidden (403)" "目录禁止索引（403）")"
  scan 'SSL_do_handshake\(\) failed|ssl handshake' ssl-handshake-failed "$(ncc_t "SSL handshake failures" "SSL 握手失败")"
  scan 'rewrite or internal redirection cycle' too-many-redirects "$(ncc_t "Internal redirect cycles" "内部重定向循环")"
  ncc_info "$(ncc_t "Scanned last ${LOG_LINES} lines of" "已扫描最后 ${LOG_LINES} 行：") ${ERRLOG}"
else
  ncc_info "$(ncc_t "Error log not readable:" "无法读取错误日志：") ${ERRLOG}"
fi

# 7. system ---------------------------------------------------------------
ncc_step "$(ncc_t "System" "系统")"
use="$(df -P / 2>/dev/null | awk 'NR==2{gsub("%","",$5); print $5}')"
if [[ -n "${use}" && "${use}" -ge 90 ]]; then
  issue "$(ncc_t "Root filesystem ${use}% full (nginx cannot write logs/temp files)." "根分区已用 ${use}%（nginx 可能写不了日志和临时文件）。")" "curl -fsSL xyz.sh/clean | bash -s -- --dry-run"
else ncc_ok "$(ncc_t "Disk / used:" "磁盘 / 已用：") ${use:-?}%"; fi
if ncc_need_cmd getenforce && [[ "$(getenforce 2>/dev/null)" == "Enforcing" ]]; then
  if [[ "${pp:-0}" -gt 0 ]] && ncc_need_cmd getsebool && getsebool httpd_can_network_connect 2>/dev/null | grep -q "off"; then
    issue "$(ncc_t "SELinux blocks nginx from connecting to upstreams (httpd_can_network_connect off)." "SELinux 禁止 nginx 连接上游（httpd_can_network_connect 为 off）。")" "setsebool -P httpd_can_network_connect 1"
  fi
fi

# 8. optional hardening ---------------------------------------------------
if [[ "${APPLY_HARDENING}" == "1" ]]; then
  ncc_step "$(ncc_t "Apply hardening (opt-in)" "应用加固（需显式开启）")"
  SNIP="/etc/nginx/conf.d/00-nginxcc-hardening.conf"
  if grep -Eq '^\s*server_tokens\s' <<<"${CONF_NC}"; then
    ncc_info "$(ncc_t "server_tokens is already set somewhere; not adding a duplicate. Edit it by hand." "server_tokens 已在别处设置，不重复添加，请手动修改。")"
  elif ! grep -q "conf.d/\*.conf" <<<"${CONF}"; then
    ncc_warn "$(ncc_t "conf.d/*.conf is not included in http {}; refusing to guess where to write." "http {} 中没有 include conf.d/*.conf，不猜测写入位置。")"
  elif ! ncc_is_root && [[ "${NCC_DRY_RUN}" != "1" ]]; then
    ncc_error "$(ncc_t "Needs root." "需要 root。")"
  elif ncc_confirm "$(ncc_t "Write ${SNIP} (server_tokens off) and reload nginx?" "写入 ${SNIP}（server_tokens off）并重载 nginx？")"; then
    printf '# Added by nginx.cc/fix --apply-hardening on %s\nserver_tokens off;\n' "$(date -u +%FT%TZ)" | ncc_write_file "${SNIP}"
    if [[ "${NCC_DRY_RUN}" != "1" ]]; then
      if nginx -t >/dev/null 2>&1; then
        if ncc_has_systemd; then systemctl reload nginx; else nginx -s reload 2>/dev/null || true; fi
        ncc_ok "$(ncc_t "Applied and reloaded." "已应用并重载。")"
      else
        rm -f "${SNIP}"
        issue "$(ncc_t "nginx -t failed after the change; rolled back." "修改后 nginx -t 失败，已回滚。")"
      fi
    fi
  else
    ncc_info "$(ncc_t "Skipped." "已跳过。")"
  fi
fi

printf '\n%s%s%s: %s %s, %s %s\n' "${C_BOLD}" "$(ncc_t "Summary" "汇总")" "${C_RESET}" "${ISSUES}" "$(ncc_t "problem(s)" "个问题")" "${WARNS}" "$(ncc_t "warning(s)" "个提醒")"
ncc_tip "$(ncc_t "Diagnose a live site:" "在线诊断网站：") ${NCC_BASE}/${NCC_LANG}/diag"
exit 0

}
