#!/usr/bin/env bash
set -Eeuo pipefail
umask 077
BASE_URL="${FASTSERVER_DOWNLOAD_BASE:-http://106.55.18.70/downloads}"
MODE='online'
CORE_SHA='dd8c3025d07fdfdf9d4c03a44a3fa1937499ac7d0d7c51954301cecf1a6ee525'
HELPER_SHA='e406bb93fc57f53794b6562f57a86678e9b8a273617b008f9083c337082fa447'
SCRIPT_DIR=''
log() { printf '[FastServer] %s\n' "$*"; }
die() { log "$*" >&2; exit 1; }
[[ ${EUID} -eq 0 ]] || die '请使用 root 执行。'
[[ $(uname -m) == x86_64 ]] || die '仅支持 Linux x86-64。'
for cmd in curl gzip sha256sum systemctl flock ss awk pgrep readlink; do command -v "$cmd" >/dev/null || die "缺少依赖：$cmd"; done
exec 9>/run/fastserver-realip-install.lock
flock -n 9 || die '另一个安装任务正在运行。'
work=$(mktemp -d /root/.fastserver-realip-install.XXXXXX)
helper_path=/usr/local/lib/fastserver/FastServerRealIP
unit=/etc/systemd/system/fastserver-realip-client.service
helper_changed=0; core_ok=0; had_helper=0; had_unit=0; was_active=0; was_enabled=0
cleanup() {
 rc=$?; trap - EXIT
 if ((helper_changed && !core_ok)); then
  log '安装未完成，恢复原辅助服务。'
  systemctl stop fastserver-realip-client.service >/dev/null 2>&1 || true
  if ((!was_enabled)); then systemctl disable fastserver-realip-client.service >/dev/null 2>&1 || true; fi
  if ((had_helper)); then cp -p "$work/helper.old" "$helper_path"; else rm -f "$helper_path"; fi
  if ((had_unit)); then cp -p "$work/unit.old" "$unit"; else rm -f "$unit"; fi
  systemctl daemon-reload || true
  if ((was_active)); then systemctl start fastserver-realip-client.service || true; fi
 fi
 rm -f "$work/helper.gz" "$work/helper" "$work/core.sh" "$work/FastServer.gz" "$work/health.json"
 rmdir "$work" 2>/dev/null || true
 exit "$rc"
}
trap cleanup EXIT
if [[ "$MODE" == offline ]]; then
 SCRIPT_DIR=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd -P)
 cp -- "$SCRIPT_DIR/FastServerRealIP.gz" "$work/helper.gz"
 cp -- "$SCRIPT_DIR/install-fastserver-core-offline-r5.sh" "$work/core.sh"
 cp -- "$SCRIPT_DIR/FastServer.gz" "$work/FastServer.gz"
else
 curl -fL --retry 3 --connect-timeout 10 --max-time 300 "$BASE_URL/FastServer-realip-helper-20261106.gz" -o "$work/helper.gz"
 curl -fL --retry 3 --connect-timeout 10 --max-time 60 "$BASE_URL/install-fastserver-core-r5.sh" -o "$work/core.sh"
fi
gzip -dc "$work/helper.gz" > "$work/helper"
[[ $(sha256sum "$work/helper" | awk '{print $1}') == "$HELPER_SHA" ]] || die '辅助程序校验失败，旧程序未停止。'
[[ $(sha256sum "$work/core.sh" | awk '{print $1}') == "$CORE_SHA" ]] || die '安装脚本校验失败，旧程序未停止。'
bash -n "$work/core.sh"
if [[ -f "$unit" ]] && ! grep -Fq "$helper_path" "$unit"; then die '发现不匹配的同名辅助服务，请先检查。'; fi
if ss -lnt 'sport = :12002' | grep -q LISTEN; then
 execinfo=$(systemctl show fastserver-realip-client.service -p ExecStart 2>/dev/null || true)
 [[ "$execinfo" == *"$helper_path"* ]] || die '本机 12002 已被其他程序使用，未改动旧程序。'
fi
systemctl is-active --quiet fastserver-realip-client.service && was_active=1 || true
systemctl is-enabled --quiet fastserver-realip-client.service 2>/dev/null && was_enabled=1 || true
if [[ -f "$helper_path" ]]; then cp -p "$helper_path" "$work/helper.old"; had_helper=1; fi
if [[ -f "$unit" ]]; then cp -p "$unit" "$work/unit.old"; had_unit=1; fi
install -d -m 755 "$(dirname "$helper_path")"
helper_changed=1
systemctl stop fastserver-realip-client.service >/dev/null 2>&1 || true
install -m 755 "$work/helper" "$helper_path.new"
mv -f "$helper_path.new" "$helper_path"
cat > "$unit" <<'UNIT'
[Unit]
Description=FastServer local real-IP API relay
Wants=network-online.target
After=network-online.target
[Service]
Type=notify
NotifyAccess=main
User=nobody
ExecStart=/usr/local/lib/fastserver/FastServerRealIP -mode client -listen 127.0.0.1:12002 -upstream http://106.55.18.70:2002
Restart=always
RestartSec=3
TimeoutStartSec=90
NoNewPrivileges=true
PrivateTmp=true
ProtectSystem=full
ProtectHome=true
LimitNOFILE=65536
[Install]
WantedBy=multi-user.target
UNIT
chmod 644 "$unit"
systemctl daemon-reload
log '识别本机公网 IP 并启动认证辅助服务。'
systemctl start fastserver-realip-client.service
curl --noproxy '*' -fsS -m 5 http://127.0.0.1:12002/__fastserver_realip_health > "$work/health.json"
log "本机公网 IP 检测：$(cat "$work/health.json")"
systemctl enable fastserver-realip-client.service >/dev/null
FASTSERVER_DOWNLOAD_BASE="$BASE_URL" bash "$work/core.sh"
core_ok=1
pid=$(pgrep -x FastServer | head -n 1 || true)
target=${FASTSERVER_PATH:-}
if [[ -z "$target" && -n "$pid" ]]; then target=$(readlink "/proc/$pid/exe" || true); fi
service=''
for candidate in FastProxy.service fastserver-managed.service; do
 execinfo=$(systemctl show "$candidate" -p ExecStart 2>/dev/null || true)
 if [[ -n "$target" && "$execinfo" == *"$target"* ]]; then service=$candidate; break; fi
done
[[ -n "$service" ]] || die '程序已更新，但未识别到主服务；辅助服务已保留，请检查启动顺序。'
mkdir -p "/etc/systemd/system/$service.d"
cat > "/etc/systemd/system/$service.d/85-fastserver-realip.conf" <<'UNIT'
[Unit]
Wants=fastserver-realip-client.service
After=fastserver-realip-client.service
UNIT
systemctl daemon-reload
log '真实公网 IP 上报版安装完成，请刷新后台确认显示。'
log '外部 API：106.55.18.70:2002；80 仅下载。认证账号验证逻辑不变。'
