#!/usr/bin/env bash
# nginx.cc/install — served payload. Common library first, then the script body.
# Verify: curl -fsSL https://nginx.cc/install.sh | sha256sum  (compare with https://nginx.cc/install.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/install body ----
# nginx.cc/install — install or update nginx from the official nginx.org repository.
#
# Usage:
#   curl -fsSL nginx.cc/install | bash                  # stable branch
#   curl -fsSL nginx.cc/install | bash -s -- --mainline # mainline branch
#   curl -fsSL nginx.cc/install | bash -s -- --dry-run  # print every step, change nothing
#   curl -fsSL nginx.cc/install | bash -s -- -y         # no prompts
#
# Supports Debian / Ubuntu (apt) and RHEL / CentOS / Rocky / AlmaLinux (yum/dnf).
# Idempotent: re-running only updates the package; the repo file is rewritten only
# if it differs. Signing key fingerprint is checked against nginx.org's published one.
# 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="install"
ncc_init "$@"

BRANCH="stable"
START=1
for a in "${NCC_ARGS[@]+"${NCC_ARGS[@]}"}"; do
  case "${a}" in
    --mainline) BRANCH="mainline" ;;
    --stable) BRANCH="stable" ;;
    --no-start) START=0 ;;
    *) ncc_warn "$(ncc_t "Unknown option ignored:" "忽略未知参数：") ${a}" ;;
  esac
done

if [[ "${NCC_HELP}" == "1" ]]; then
  cat <<HELP
$(ncc_t "Install/update nginx from nginx.org." "从 nginx.org 官方源安装或更新 nginx。")
  --stable      $(ncc_t "stable branch (default)" "稳定版（默认）")
  --mainline    $(ncc_t "mainline branch" "主线版")
  --no-start    $(ncc_t "do not enable/start the service" "不启用、不启动服务")
  --dry-run     $(ncc_t "print every step, change nothing" "只打印步骤，不做修改")
  -y            $(ncc_t "assume yes" "自动确认")
HELP
  exit 0
fi

KEY_URL="https://nginx.org/keys/nginx_signing.key"
KEY_FPR="573BFD6B3D8FBC641079A6ABABF5BD827BD9BF62"
KEYRING="/usr/share/keyrings/nginx-archive-keyring.gpg"
PREFIX=""; [[ "${BRANCH}" == "mainline" ]] && PREFIX="mainline/"

if ! ncc_is_root && [[ "${NCC_DRY_RUN}" != "1" ]]; then
  ncc_error "$(ncc_t "Run as root (sudo bash), or add --dry-run to preview." "请用 root 运行（sudo bash），或加 --dry-run 预览。")"
  exit 1
fi

ncc_info "$(ncc_t "System:" "系统：") ${NCC_OS_PRETTY} (${NCC_OS_FAMILY})"
ncc_info "$(ncc_t "Branch:" "分支：") ${BRANCH}"
ncc_info "$(ncc_t "Upstream:" "上游：") https://nginx.org/en/linux_packages.html"

current_version() { if ncc_need_cmd nginx; then nginx -v 2>&1 | sed -n 's|.*nginx/||p'; fi; }
BEFORE="$(current_version || true)"
if [[ -n "${BEFORE}" ]]; then
  ncc_info "$(ncc_t "Installed nginx:" "当前 nginx：") ${BEFORE}"
else
  ncc_info "$(ncc_t "nginx is not installed yet." "尚未安装 nginx。")"
fi

check_url() { curl -fsSIL -o /dev/null --max-time 15 "$1"; }

install_debian() {
  local distro="${NCC_OS_ID}" codename="${NCC_OS_CODENAME}"
  case " ${NCC_OS_ID} ${NCC_OS_LIKE} " in *" ubuntu "*) distro="ubuntu" ;; *) distro="debian" ;; esac
  [[ "${NCC_OS_ID}" == "ubuntu" ]] && distro="ubuntu"
  if [[ -z "${codename}" ]]; then ncc_error "$(ncc_t "Cannot detect release codename." "无法识别发行版代号。")"; exit 1; fi
  local repo_url="https://nginx.org/packages/${PREFIX}${distro}"
  if ncc_need_cmd curl && ! check_url "https://nginx.org/packages/${PREFIX}${distro}/dists/${codename}/Release"; then
    ncc_error "$(ncc_t "nginx.org has no ${BRANCH} packages for ${distro} ${codename}." "nginx.org 没有 ${distro} ${codename} 的 ${BRANCH} 软件包。")"
    exit 1
  fi
  local list_line="deb [signed-by=${KEYRING}] ${repo_url} ${codename} nginx"
  local list_file="/etc/apt/sources.list.d/nginx.list"

  if dpkg -s nginx >/dev/null 2>&1 && ! dpkg -s nginx 2>/dev/null | grep -q "nginx-packaging@f5.com\|NGINX Packaging"; then
    ncc_warn "$(ncc_t "The installed nginx comes from the distro. Switching to nginx.org packages replaces it (configs in /etc/nginx are kept by dpkg, but sites-enabled layout differs)." "当前 nginx 来自系统源。切换到 nginx.org 包会替换它（/etc/nginx 下的配置由 dpkg 保留，但 sites-enabled 目录结构不同）。")"
    ncc_confirm "$(ncc_t "Switch to nginx.org packages?" "切换到 nginx.org 官方包？")" || { ncc_info "$(ncc_t "Cancelled." "已取消。")"; exit 0; }
  fi

  ncc_step "$(ncc_t "Prerequisites" "安装依赖")"
  ncc_run env DEBIAN_FRONTEND=noninteractive apt-get update -qq
  ncc_run env DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends curl gnupg2 ca-certificates

  ncc_step "$(ncc_t "Signing key" "签名密钥") ${KEY_URL}"
  if [[ "${NCC_DRY_RUN}" == "1" ]]; then
    ncc_run "curl -fsSL ${KEY_URL} | gpg --dearmor > ${KEYRING}  # verify fingerprint ${KEY_FPR}"
  else
    local tmp; tmp="$(mktemp)"
    curl -fsSL "${KEY_URL}" -o "${tmp}"
    if ! gpg --show-keys --with-colons "${tmp}" 2>/dev/null | grep -q "^fpr:*${KEY_FPR}:"; then
      rm -f "${tmp}"
      ncc_error "$(ncc_t "Signing key fingerprint mismatch. Aborting." "签名密钥指纹不匹配，已中止。")"; exit 1
    fi
    gpg --dearmor < "${tmp}" > "${KEYRING}.tmp" && mv "${KEYRING}.tmp" "${KEYRING}"
    rm -f "${tmp}"
    ncc_ok "$(ncc_t "Fingerprint verified:" "指纹已核验：") ${KEY_FPR}"
  fi

  ncc_step "$(ncc_t "Repository" "软件源") ${list_file}"
  if [[ -f "${list_file}" ]] && [[ "$(cat "${list_file}")" == "${list_line}" ]]; then
    ncc_ok "$(ncc_t "Already configured." "已配置，跳过。")"
  else
    printf '%s\n' "${list_line}" | ncc_write_file "${list_file}"
  fi
  printf 'Package: *\nPin: origin nginx.org\nPin: release o=nginx\nPin-Priority: 900\n' | ncc_write_file /etc/apt/preferences.d/99nginx

  ncc_step "$(ncc_t "Install / update nginx" "安装 / 更新 nginx")"
  ncc_run env DEBIAN_FRONTEND=noninteractive apt-get update -qq
  ncc_run env DEBIAN_FRONTEND=noninteractive apt-get install -y -qq -o Dpkg::Options::=--force-confold nginx
}

install_rhel() {
  if [[ "${NCC_OS_ID}" == "fedora" ]]; then
    ncc_error "$(ncc_t "nginx.org does not publish Fedora packages. Use: dnf install nginx" "nginx.org 不提供 Fedora 包，请用：dnf install nginx")"; exit 1
  fi
  local major="${NCC_OS_VERSION%%.*}" arch; arch="$(uname -m)"
  if ncc_need_cmd curl && ! check_url "https://nginx.org/packages/${PREFIX}centos/${major}/${arch}/repodata/repomd.xml"; then
    ncc_error "$(ncc_t "nginx.org has no packages for EL${major} ${arch}." "nginx.org 没有 EL${major} ${arch} 的软件包。")"; exit 1
  fi
  local repo_file="/etc/yum.repos.d/nginx.repo" content
  content="[nginx-${BRANCH}]
name=nginx ${BRANCH} repo
baseurl=https://nginx.org/packages/${PREFIX}centos/\$releasever/\$basearch/
gpgcheck=1
enabled=1
gpgkey=${KEY_URL}
module_hotfixes=true"
  local pm="dnf"; ncc_need_cmd dnf || pm="yum"

  if rpm -q nginx >/dev/null 2>&1 && ! rpm -qi nginx 2>/dev/null | grep -qi "nginx.org\|NGINX Packaging\|nginx-packaging"; then
    ncc_warn "$(ncc_t "The installed nginx comes from the distro/EPEL; nginx.org packages will replace it." "当前 nginx 来自系统源/EPEL，nginx.org 包会替换它。")"
    ncc_confirm "$(ncc_t "Switch to nginx.org packages?" "切换到 nginx.org 官方包？")" || { ncc_info "$(ncc_t "Cancelled." "已取消。")"; exit 0; }
  fi

  ncc_step "$(ncc_t "Repository" "软件源") ${repo_file}"
  if [[ -f "${repo_file}" ]] && [[ "$(cat "${repo_file}")" == "${content}" ]]; then
    ncc_ok "$(ncc_t "Already configured." "已配置，跳过。")"
  else
    printf '%s\n' "${content}" | ncc_write_file "${repo_file}"
  fi
  ncc_step "$(ncc_t "Signing key (fingerprint must be" "签名密钥（指纹应为") ${KEY_FPR})"
  if [[ "${NCC_DRY_RUN}" == "1" ]]; then
    ncc_run rpmkeys --import "${KEY_URL}"
  else
    local tmp; tmp="$(mktemp)"
    curl -fsSL "${KEY_URL}" -o "${tmp}"
    if ncc_need_cmd gpg && ! gpg --show-keys --with-colons "${tmp}" 2>/dev/null | grep -q "^fpr:*${KEY_FPR}:"; then
      rm -f "${tmp}"; ncc_error "$(ncc_t "Signing key fingerprint mismatch. Aborting." "签名密钥指纹不匹配，已中止。")"; exit 1
    fi
    rpmkeys --import "${tmp}"; rm -f "${tmp}"
    ncc_ok "$(ncc_t "Key imported." "密钥已导入。")"
  fi
  ncc_step "$(ncc_t "Install / update nginx" "安装 / 更新 nginx")"
  if rpm -q nginx >/dev/null 2>&1; then
    ncc_run "${pm}" -y -q upgrade nginx
  else
    ncc_run "${pm}" -y -q install nginx
  fi
}

case "${NCC_OS_FAMILY}" in
  debian) install_debian ;;
  rhel) install_rhel ;;
  *) ncc_error "$(ncc_t "Unsupported system. Supported: Debian, Ubuntu, RHEL/CentOS/Rocky/AlmaLinux." "不支持的系统。支持：Debian、Ubuntu、RHEL/CentOS/Rocky/AlmaLinux。")"; exit 1 ;;
esac

if [[ "${START}" == "1" ]]; then
  if ncc_has_systemd; then
    ncc_step "$(ncc_t "Enable and (re)start service" "启用并启动服务")"
    ncc_run systemctl enable nginx
    if [[ "${NCC_DRY_RUN}" == "1" ]] || nginx -t >/dev/null 2>&1; then
      ncc_run systemctl restart nginx
    else
      ncc_warn "$(ncc_t "nginx -t failed; service not restarted. Run: curl -fsSL nginx.cc/fix | bash" "nginx -t 失败，未重启服务。可运行：curl -fsSL nginx.cc/fix | bash")"
    fi
  else
    ncc_info "$(ncc_t "No systemd detected; skipped service start." "未检测到 systemd，跳过启动服务。")"
  fi
fi

AFTER="$(current_version || true)"
if [[ "${NCC_DRY_RUN}" == "1" ]]; then
  ncc_ok "$(ncc_t "Dry run finished. Nothing was changed." "演练结束，未做任何修改。")"
else
  ncc_ok "$(ncc_t "nginx version:" "nginx 版本：") ${BEFORE:-none} -> ${AFTER:-unknown}"
  ncc_tip "$(ncc_t "Next: check your config with  curl -fsSL nginx.cc/fix | bash" "下一步：用 curl -fsSL nginx.cc/fix | bash 体检配置")"
fi

}
