#!/bin/sh

export PATH="/bin:/sbin:/usr/bin:/usr/sbin:${PATH:-}"

CONFIG="owrtremote"
SECTION="main"
# OpenWrt packages are published by yichya for the architectures reported by
# opkg/apk. The default is release discovery: the router asks GitHub for the
# published assets and validates each candidate before replacing Xray. An
# explicit XRAY_RELEASE_VERSION is retained as an administrator/test filter,
# never as the default package version.
XRAY_RELEASE_REPO="${XRAY_RELEASE_REPO:-https://github.com/yichya/openwrt-xray}"
XRAY_RELEASE_VERSION="${XRAY_RELEASE_VERSION:-}"
XRAY_RELEASE_API_URL="${XRAY_RELEASE_API_URL:-https://api.github.com/repos/yichya/openwrt-xray/releases}"

log() {
	# procd already captures stderr. Use only logger for managed processes.
	[ "${OWRT_REMOTE_SERVICE_LOG:-0}" = 1 ] || printf '%s\n' "$*" >&2
	logger -t owrt-remote "$*" 2>/dev/null || true
}

die() {
	log "ОШИБКА: $*"
	exit 1
}

usage() {
	cat <<'EOF'
Использование:
  owrt-remote status
  owrt-remote doctor
  owrt-remote install-xray-tmp
  owrt-remote prepare-xray
  owrt-remote xray-package-diagnostics
  owrt-remote stop-xray
  owrt-remote render-client [--stdout]
  owrt-remote run
  owrt-remote heartbeat
  owrt-remote heartbeat-loop
  owrt-remote heartbeat-diagnostics
  owrt-remote tachyon-status
  owrt-remote logs-sync
  owrt-remote network-diagnostics

Настройки лежат в /etc/config/owrtremote.
EOF
}

uci_get() {
	local key default value
	key="$1"
	default="$2"
	value="$(uci -q get "$CONFIG.$SECTION.$key" 2>/dev/null || true)"
	[ -n "$value" ] && {
		printf '%s' "$value"
		return
	}
	printf '%s' "$default"
}

truthy() {
	case "$1" in
		1|yes|true|on|enabled) return 0 ;;
		*) return 1 ;;
	esac
}

json_escape() {
	# The final sentinel retains trailing newlines through awk's record split.
	printf '%s.' "$1" | LC_ALL=C awk '
		BEGIN { for (i = 1; i < 32; i++) escape[sprintf("%c", i)] = sprintf("\\u%04x", i) }
		{ if (NR > 1) value = value "\n"; value = value $0 }
		END {
			value = substr(value, 1, length(value) - 1)
			for (i = 1; i <= length(value); i++) {
				char = substr(value, i, 1)
				if (char == "\\") printf "\\\\"
				else if (char == "\"") printf "\\\""
				else if (char in escape) printf "%s", escape[char]
				else printf "%s", char
			}
		}'
}

json_string() {
	printf '"%s"' "$(json_escape "$1")"
}

safe_num() {
	case "$1" in
		''|*[!0-9]*) printf '%s' "$2" ;;
		*) printf '%s' "$1" ;;
	esac
}

safe_id() {
	printf '%s' "$1" | tr -cs 'A-Za-z0-9._-' '-'
}

normalize_url_base() {
	local value
	value="${1%/}"
	printf '%s' "$value"
}

json_unescape_basic() {
	printf '%s' "$1" | sed 's/\\"/"/g; s/\\\\/\\/g'
}

json_extract_object_string() {
	local file object key compact value
	file="$1"
	object="$2"
	key="$3"
	compact="$(tr -d '\r\n' <"$file" 2>/dev/null || true)"
	[ -n "$compact" ] || return 0
	value="$(printf '%s' "$compact" | sed -n "s/.*\"$object\"[[:space:]]*:[[:space:]]*{[^}]*\"$key\"[[:space:]]*:[[:space:]]*\"\\([^\"]*\\)\".*/\\1/p" | head -n 1)"
	json_unescape_basic "$value"
}

uci_set_if_changed() {
	local key next current
	key="$1"
	next="$2"
	[ -n "$next" ] || return 1
	current="$(uci_get "$key" '')"
	[ "$current" = "$next" ] && return 1
	uci -q set "$CONFIG.$SECTION.$key=$next" >/dev/null 2>&1 || return 1
	return 0
}

# Existing installations also default to manual: only an explicit opt-in may
# let a heartbeat replace the administrator's tunnel endpoint.
vps_host_mode() {
	case "$(uci_get vps_host_mode manual)" in
		auto) printf auto ;;
		*) printf manual ;;
	esac
}

WAN_HELPER="${OWRT_REMOTE_WAN_HELPER:-/usr/lib/owrt-remote/wan.sh}"
if [ -r "$WAN_HELPER" ]; then
	. "$WAN_HELPER"
fi
CONTROL_HELPER="${OWRT_REMOTE_CONTROL_HELPER:-/usr/lib/owrt-remote/control.sh}"
if [ -r "$CONTROL_HELPER" ]; then
	. "$CONTROL_HELPER"
else
	xray_control_stopped() { return 1; }
	xray_control_result_json() { printf null; }
	xray_control_dispatch() { return 0; }
fi
TACHYON_HELPER="${OWRT_REMOTE_TACHYON_HELPER:-/usr/lib/owrt-remote/tachyon.sh}"
if [ -r "$TACHYON_HELPER" ]; then
    . "$TACHYON_HELPER"
else
    tachyon_json() { printf '{"checked":false}'; }
    tachyon_tunnel_port() { printf 0; }
    tachyon_reconcile_xray() { :; }
fi

host_model() {
	if [ -r /tmp/sysinfo/model ]; then
		cat /tmp/sysinfo/model
		return
	fi
	if [ -r /proc/device-tree/model ]; then
		tr -d '\000' </proc/device-tree/model
		return
	fi
	printf 'OpenWrt router'
}

board_name() {
	if [ -r /tmp/sysinfo/board_name ]; then
		cat /tmp/sysinfo/board_name
		return
	fi
	printf 'unknown'
}

release_text() {
	if [ -r /etc/openwrt_release ]; then
		(
			. /etc/openwrt_release 2>/dev/null
			printf '%s %s' "${DISTRIB_ID:-OpenWrt}" "${DISTRIB_RELEASE:-unknown}"
		)
		return
	fi
	printf 'OpenWrt unknown'
}

uptime_seconds() {
	if [ -r /proc/uptime ]; then
		cut -d. -f1 /proc/uptime
		return
	fi
	printf '0'
}

load_text() {
	if [ -r /proc/loadavg ]; then
		awk '{print $1" "$2" "$3}' /proc/loadavg
		return
	fi
	printf '0 0 0'
}

memory_text() {
	if [ -r /proc/meminfo ]; then
		awk '
			/^MemTotal:/ { total=$2 }
			/^MemAvailable:/ { avail=$2 }
			/^MemFree:/ && avail=="" { avail=$2 }
			END {
				if (total == "") total = 0
				if (avail == "") avail = 0
				printf "%s/%s kB", avail, total
			}
		' /proc/meminfo
		return
	fi
	printf '0/0 kB'
}

flash_text() {
	local mount text
	text="$(
		df -kP 2>/dev/null | awk '
			function mb(k) {
				if (k == "" || k == 0) return "0 MB"
				return sprintf("%.1f MB", k / 1024)
			}
			NR == 1 { next }
			{
				mount = $NF
				total = $(NF-4)
				avail = $(NF-2)
				pct = $(NF-1)
				gsub(/%/, "", pct)
				if (total !~ /^[0-9]+$/ || avail !~ /^[0-9]+$/ || pct !~ /^[0-9]+$/) next

				score = 0
				if (mount == "/overlay" || mount == "/rom/overlay") score = 400
				else if (mount == "/") score = 300
				else if ($1 == "overlayfs:/overlay") score = 250
				else if (mount ~ /^\/overlay(\/|$)/) score = 200
				if (score <= best_score) next

				best_score = score
				best_total = total
				best_avail = avail
				best_pct = pct
			}
			END {
				if (best_score > 0) {
					printf "%s free / %s (%s%% used)", mb(best_avail), mb(best_total), best_pct
				}
			}
		'
	)"
	if [ -n "$text" ]; then
		printf '%s' "$text"
		return
	fi
	for mount in /overlay /rom/overlay /; do
		text="$(
			df -kP "$mount" 2>/dev/null | awk '
				function mb(k) {
					if (k == "" || k == 0) return "0 MB"
					return sprintf("%.1f MB", k / 1024)
				}
				NR == 1 { next }
				NF >= 5 {
					total = $(NF-4)
					avail = $(NF-2)
					pct = $(NF-1)
					gsub(/%/, "", pct)
					if (total ~ /^[0-9]+$/ && avail ~ /^[0-9]+$/ && pct ~ /^[0-9]+$/) {
						printf "%s free / %s (%s%% used)", mb(avail), mb(total), pct
						exit
					}
				}
			'
		)"
		if [ -n "$text" ]; then
			printf '%s' "$text"
			return
		fi
	done
	printf 'unknown'
}

temperature_text() {
	local file raw max
	max=""
	for file in /sys/class/thermal/thermal_zone*/temp /sys/devices/virtual/thermal/thermal_zone*/temp /sys/class/hwmon/hwmon*/temp*_input; do
		[ -r "$file" ] || continue
		raw="$(cat "$file" 2>/dev/null | tr -cd '0-9-')"
		[ -n "$raw" ] || continue
		case "$raw" in
			-*|'') continue ;;
		esac
		[ -z "$max" ] && max="$raw"
		[ "$raw" -gt "$max" ] && max="$raw"
	done
	if [ -n "$max" ]; then
		awk -v t="$max" 'BEGIN { if (t > 1000) printf "%.1f C", t / 1000; else printf "%s C", t }'
		return
	fi
	printf 'unknown'
}

ps_all() {
	ps w 2>/dev/null || ps 2>/dev/null || true
}

xray_pids() {
	local config cmdline cmd pid
	config="$(uci_get xray_config /etc/xray/owrt-remote-client.json)"
	[ -n "$config" ] || return 0
	for cmdline in /proc/[0-9]*/cmdline; do
		[ -r "$cmdline" ] || continue
		cmd="$(tr '\000' ' ' <"$cmdline" 2>/dev/null || true)"
		case "$cmd" in
			*xray*"$config"*|*xray-core*"$config"*)
				pid="${cmdline%/cmdline}"
				pid="${pid##*/}"
				printf '%s\n' "$pid"
				;;
		esac
	done
}

xray_running() {
	[ -n "$(xray_pids)" ]
}

stop_xray() {
	local pids pid alive
	pids="$(xray_pids)"
	if [ -z "$pids" ]; then
		printf '%s\n' "OK: Xray уже остановлен"
		return 0
	fi
	for pid in $pids; do
		kill "$pid" >/dev/null 2>&1 || true
	done
	sleep 1
	alive=""
	for pid in $pids; do
		if kill -0 "$pid" >/dev/null 2>&1; then
			kill -9 "$pid" >/dev/null 2>&1 || true
			alive="$alive $pid"
		fi
	done
	if [ -n "$alive" ]; then
		printf 'OK: Xray остановлен принудительно:%s\n' "$alive"
	else
		printf '%s\n' "OK: Xray остановлен"
	fi
}

ssh_running() {
	ps_all | grep '[d]ropbear' >/dev/null 2>&1
}

active_ssh_session() {
	local port hex file
	port="$(safe_num "$(uci_get ssh_port 22)" 22)"
	hex="$(printf '%04X' "$port" 2>/dev/null || printf '0016')"
	for file in /proc/net/tcp /proc/net/tcp6; do
		[ -r "$file" ] || continue
		awk -v port="$hex" '
			NR > 1 {
				split($2, local_addr, ":")
				if (local_addr[2] == port && $4 == "01") {
					found = 1
				}
			}
			END { exit found ? 0 : 1 }
		' "$file" 2>/dev/null && return 0
	done
	return 1
}

xray_bin_path() {
	local configured candidate
	configured="$(uci_get xray_bin /usr/bin/xray)"
	if [ -x "$configured" ]; then
		printf '%s' "$configured"
		return
	fi
	for candidate in /usr/bin/xray /usr/bin/xray-core /usr/local/bin/xray /opt/bin/xray /tmp/owrt-xray/xray /tmp/owrt-xray/xray_softfloat /tmp/xray /tmp/xray_softfloat; do
		if [ -x "$candidate" ]; then
			printf '%s' "$candidate"
			return
		fi
	done
	candidate="$(command -v xray 2>/dev/null || command -v xray-core 2>/dev/null || true)"
	if [ -n "$candidate" ] && [ -x "$candidate" ]; then
		printf '%s' "$candidate"
		return
	fi
	printf '%s' "$configured"
}

xray_openwrt_info() (
	. "${OWRT_REMOTE_RELEASE_FILE:-/etc/openwrt_release}" 2>/dev/null || return 1
	case "$1" in arch) printf '%s' "${DISTRIB_ARCH:-}" ;; release) printf '%s' "${DISTRIB_RELEASE:-}" ;; esac
)
xray_arch() {
	local arch precise
	if command -v apk >/dev/null 2>&1; then
		arch="$(apk --print-arch 2>/dev/null)" || return 1
		precise="$(xray_openwrt_info arch)"
		# Old APK reports a generic ABI (mipsel); the OpenWrt target gives
		# the instruction set. Never guess 24kc/74kc from mipsel alone.
		case "$arch:$precise" in
			mipsel:mipsel_*|mips:mips_*|aarch64:aarch64_*|arm*:arm_*|x86:x86_*) arch="$precise" ;;
		esac
	elif command -v opkg >/dev/null 2>&1; then
		arch="$(opkg print-architecture 2>/dev/null | awk '$1=="arch" && $2!="all" && $2!="noarch" && $3>=p {a=$2;p=$3} END {print a}')"
	else
		arch="$(xray_openwrt_info arch)"
	fi
	case "$arch" in ''|*[!A-Za-z0-9_.-]*) log 'Xray: cannot determine precise OpenWrt architecture'; return 1 ;; esac
	printf '%s\n' "$arch"
}
xray_package_format() {
	if command -v apk >/dev/null 2>&1; then printf 'apk\n'
	elif command -v opkg >/dev/null 2>&1; then printf 'ipk\n'
	else return 1; fi
}
xray_version_allowed() {
	# A capability boundary, not a pinned download version. Every selected
	# binary is also tested; newer releases reject our public VLESS transport.
	LC_ALL=C awk -v v="${1#v}" 'BEGIN {n=split(v,a,"."); exit !(n==3 && v~/^[0-9]+\.[0-9]+\.[0-9]+$/ && a[1]*10000+a[2]*100+a[3]<260711)}'
}
xray_json() { jsonfilter -i "$1" -e "$2"; }
xray_release_asset() {
	local arch
	# Naming the cache must never perform a network request.
	arch="$(xray_arch)" || return 1
	printf 'xray-%s' "$arch"
}
xray_discover_releases() (
	dest="$1"; work="$2"; arch="$(xray_arch)" || return 1
	fmt="$(xray_package_format)" || return 1
	command -v jsonfilter >/dev/null 2>&1 || install_package jsonfilter || return 1
	log "Xray: detected architecture: $arch; packages=$fmt; OpenWrt=$(xray_openwrt_info release)"
	log 'Xray: searching compatible releases...'
	: >"$dest"
	rm -f "$work/next-release-page"
	# Bound API memory and calls: 20 releases/page, at most 200 releases.
	# Older pages are fetched on demand after candidates fail validation.
	page="${3:-1}"
	while [ "$page" -le 10 ]; do
		DOWNLOAD_STAGE=xray-releases fetch_file "$XRAY_RELEASE_API_URL?per_page=20&page=$page" "$work/releases.json" || {
			rc=$?; log "ERROR: GitHub API unavailable (rc=$rc); existing Xray preserved"; return "$rc";
		}
		[ "$(wc -c <"$work/releases.json")" -le 2097152 ] || return 1
		# Validate JSON, including an empty array. API error objects fail closed.
		xray_json "$work/releases.json" '@' >"$work/parsed" || { log 'Xray: invalid Releases API JSON'; return 1; }
		case "$(head -c 1 "$work/parsed")" in '[') ;; *) log 'Xray: Releases API returned an error object'; return 1 ;; esac
		r=0; count=0
		while [ "$r" -lt 20 ]; do
			tag="$(xray_json "$work/releases.json" "@[$r].tag_name" 2>/dev/null)"
			[ -n "$tag" ] || break
			count=$((count+1))
			rpath="@[$r]"; r=$((r+1))
			[ "$(xray_json "$work/releases.json" "$rpath.draft")" = false ] || continue
			[ "$(xray_json "$work/releases.json" "$rpath.prerelease")" = false ] || continue
			xray_version_allowed "$tag" || continue
			[ -z "$XRAY_RELEASE_VERSION" ] || [ "${tag#v}" = "${XRAY_RELEASE_VERSION#v}" ] || continue
			# Field paths come only from numeric indexes and validated names.
			xray_json "$work/releases.json" "$rpath.assets[*].name" >"$work/names" || continue
			a=0
			while IFS= read -r name; do
				apath="$rpath.assets[$a]"; a=$((a+1))
				case "$name" in *[!A-Za-z0-9_.+-]*|'') continue ;; esac
				case "$fmt:$name" in
					apk:openwrt-xray-*-"$arch".apk|ipk:openwrt-xray_*_"$arch".ipk|ipk:openwrt-xray_*-"$arch".ipk) ;;
					*) continue ;;
				esac
				url="$(xray_json "$work/releases.json" "$apath.browser_download_url")"
				digest="$(xray_json "$work/releases.json" "$apath.digest")"; digest="${digest#sha256:}"
				size="$(xray_json "$work/releases.json" "$apath.size")"
				[ "$(xray_json "$work/releases.json" "$apath.state")" = uploaded ] || continue
				case "$url" in "$XRAY_RELEASE_REPO/releases/download/$tag/$name") ;; *) continue ;; esac
				case "$digest" in *[!0-9a-f]*|'') continue ;; esac
				[ "${#digest}" = 64 ] || continue
				case "$size" in *[!0-9]*|'') continue ;; esac
				[ "$size" -gt 0 ] && [ "$size" -le 33554432 ] || continue
				printf '%s|%s|%s|%s|%s\n' "$tag" "$name" "$url" "$digest" "$size" >>"$dest"
			done <"$work/names"
		done
		# Try matching assets newest-first; bookmark older pages for the caller
		# if every candidate fails metadata/binary/transport validation.
		if [ -s "$dest" ]; then
			awk -F '|' '{v=$1; sub(/^v/,"",v); split(v,a,"."); print a[1]*10000+a[2]*100+a[3] "|" $0}' "$dest" |
				sort -t '|' -k1,1nr | cut -d '|' -f2- >"$dest.sorted" || return 1
			mv -f "$dest.sorted" "$dest" || return 1
			if [ "$count" = 20 ] && [ "$page" -lt 10 ]; then
				printf '%s\n' "$((page+1))" >"$work/next-release-page" || return 1
			fi
			return 0
		fi
		[ "$count" = 20 ] || break
		page=$((page+1))
	done
	log "ERROR: No compatible Xray package found for this device ($arch/$fmt)"
	return 1
)
xray_check_package_metadata() (
	package="$1"; work="$2"; arch="$(xray_arch)" || return 1
	case "$3" in
		*.apk)
			apk adbdump --format json "$package" >"$work/meta.json" 2>"$work/meta.err" || {
				log 'Xray: APK metadata/format unsupported by installed apk'; head -c 4096 "$work/meta.err" >&2; return 1;
			}
			name="$(xray_json "$work/meta.json" '@.info.name')"
			pkg_arch="$(xray_json "$work/meta.json" '@.info.arch')"
			[ "$name" = openwrt-xray ] || { log 'Xray: unexpected APK package name'; return 1; }
			# Metadata must match apk ABI as well as the precise asset target.
			native="$(apk --print-arch)" || return 1
			[ "$pkg_arch" = "$native" ] || [ "$pkg_arch" = "$arch" ] || { log "Xray: incompatible APK ABI: $pkg_arch (expected $native/$arch)"; return 1; }
			# Resolve dependencies against THIS firmware/installed DB without
			# installing the downloaded package or touching a running /usr/bin/xray.
			apk add --simulate --no-network --allow-untrusted "$package" >"$work/deps.out" 2>&1 || {
				log 'Xray: APK dependencies incompatible with this OpenWrt; candidate rejected'
				head -c 4096 "$work/deps.out" >&2; return 1;
			}
			;;
		*.ipk)
			if command -v ar >/dev/null 2>&1 && ar t "$package" 2>/dev/null | grep -q control.tar.gz; then
				ar p "$package" control.tar.gz >"$work/control.tar.gz" || return 1
			else
				(cd "$work" && tar -xzf "$package" ./control.tar.gz) || return 1
			fi
			(cd "$work" && tar -xzf control.tar.gz ./control) || return 1
			name="$(sed -n 's/^Package: *//p' "$work/control" | tr -d '\r')"
			[ "$name" = openwrt-xray ] || { log 'Xray: unexpected IPK package name'; return 1; }
			pkg_arch="$(sed -n 's/^Architecture: *//p' "$work/control" | tr -d '\r')"
			[ "$pkg_arch" = "$arch" ] || { log "Xray: incompatible IPK ABI: $pkg_arch (expected $arch)"; return 1; }
			deps="$(sed -n 's/^Depends: *//p' "$work/control")"
			# yichya Go packages normally depend only on libc. Unknown/versioned
			# dependencies fail closed instead of ignoring another firmware ABI.
			for dep in $(printf '%s' "$deps" | tr ',' ' '); do
				case "$dep" in *[!A-Za-z0-9_+.-]*) log "Xray: unsupported IPK dependency constraint: $deps"; return 1 ;; esac
				opkg status "$dep" | grep -q '^Status: .* installed$' || { log "Xray: missing dependency: $dep"; return 1; }
			done
			;;
		*) return 1 ;;
	esac
)

xray_package_diagnostics() {
	local bin store
	printf 'OpenWrt: %s\nArchitecture: %s\nPackage format: %s\n' "$(xray_openwrt_info release)" "$(xray_arch)" "$(xray_package_format)"
	bin="$(xray_bin_path)"
	printf 'Xray binary: %s\n' "$bin"
	if [ -x "$bin" ]; then "$bin" version | head -n 1; else printf 'Xray binary missing\n'; fi
	store="$(xray_cache_dir)" || { printf 'Persistent cache unavailable\n'; return 1; }
	printf 'Persistent cache: %s\n' "$store"
	ls -ln "$store"/*.gz 2>/dev/null || return 1
}

service_enabled() {
	/etc/init.d/owrt-remote enabled >/dev/null 2>&1
}

xray_apply_trace() {
	[ -z "${OWRT_REMOTE_APPLY_TRACE:-}" ] || printf '%s\n' "$1" >>"$OWRT_REMOTE_APPLY_TRACE"
	return 0
}

xray_valid_uuid() {
	[ "${#1}" = 36 ] || return 1
	printf '%s\n' "$1" | LC_ALL=C grep -Eq '^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$'
}

xray_port() {
	LC_ALL=C awk -v value="$2" -v field="$1" 'BEGIN {
		if (value !~ /^[0-9]+$/ || value + 0 < 1 || value + 0 > 65535) {
			printf "ОШИБКА: %s должен быть целым числом от 1 до 65535\n", field > "/dev/stderr"
			exit 1
		}
		printf "%d", value + 0
	}'
}

xray_valid_tag() {
	[ -n "$2" ] || { log "ОШИБКА: $1 пустой"; return 1; }
	# OpenWrt's BusyBox tr normally has character classes disabled. Use
	# explicit ASCII bytes; [:space:][:cntrl:] would delete ordinary letters.
	if [ "$(printf '%s' "$2" | LC_ALL=C tr -d '\001-\040\177')" != "$2" ]; then
		log "ОШИБКА: $1 содержит пробел или управляющий символ; метка должна сохраняться из OpenWrt config без изменений"
		return 1
	fi
	case "$2" in router-admin|router-ssh|vps-interconn|vps-ssh-interconn)
		log "ОШИБКА: $1 совпадает с внутренней меткой клиента"; return 1 ;;
	esac
}

validate_xray_config() {
	local file binary rc
	file="$1"
	binary="$(xray_bin_path)"
	[ -s "$file" ] || { log "ОШИБКА: конфигурация Xray отсутствует или пуста: $file"; return 1; }
	[ -x "$binary" ] || { log "ОШИБКА: Xray не найден или не исполняемый: $binary"; return 1; }
	printf 'Проверка Xray: %s -test -config %s\n' "$binary" "$file" >&2
	if "$binary" -test -config "$file" >&2; then
		return 0
	else
		rc=$?
		printf 'Проверка Xray не пройдена (rc=%s). Рабочий JSON не заменён.\n' "$rc" >&2
		return "$rc"
	fi
}

xray_requires_legacy_replacement() {
	local version
	# Keep an existing working core. Replace a known incompatible core only
	# for the transport generated here.
	if [ "$(uci_get security none)" = reality ]; then
		# Reality needs a core with X25519/Reality support; replace only old builds.
		version="$("$1" version 2>/dev/null | sed -n '1s/^Xray \([0-9][0-9.]*\) .*/\1/p')"
		[ -n "$version" ] || return 1
		LC_ALL=C awk -v version="$version" 'BEGIN {
			n=split(version, v, ".")
			exit !(n==3 && (v[1]*10000 + v[2]*100 + v[3]) < 240214)
		}'
		return $?
	fi
	# (VLESS encryption=none, security=none path, upstream rule)
	[ "$(uci_get vless_encryption none)" = none ] || return 1
	version="$("$1" version 2>/dev/null | sed -n '1s/^Xray \([0-9][0-9.]*\) .*/\1/p')"
	[ -n "$version" ] || return 1
	LC_ALL=C awk -v version="$version" 'BEGIN {
		n=split(version, v, ".")
		exit !(n==3 && (v[1]*10000 + v[2]*100 + v[3]) >= 260711)
	}'
}

xray_validate_transport_binary() (
	# Validate actual protocol support, not just `xray version`. This probe
	# contains no router credentials, does not connect and does not alter UCI.
	binary="$1"
	probe="$(mktemp -d "$(xray_runtime_dir)/.compat.XXXXXX")" || return 1
	trap 'rm -rf "$probe"' EXIT
	trap 'exit 1' INT TERM
	umask 077
	if [ "$(uci_get security none)" = reality ]; then
		cat >"$probe/config.json" <<'EOF'
{"log":{"loglevel":"none"},"outbounds":[{"tag":"vps-interconn","protocol":"vless","settings":{"address":"example.com","port":8443,"id":"11111111-1111-4111-8111-111111111111","encryption":"none","reverse":{"tag":"compat-reverse"}},"streamSettings":{"network":"tcp","security":"reality","realitySettings":{"show":false,"fingerprint":"chrome","serverName":"www.microsoft.com","publicKey":"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"}}}]}
EOF
	else
		cat >"$probe/config.json" <<'EOF'
{"log":{"loglevel":"none"},"outbounds":[{"tag":"vps-interconn","protocol":"vless","settings":{"address":"example.com","port":8443,"id":"11111111-1111-4111-8111-111111111111","encryption":"none","reverse":{"tag":"compat-reverse"}},"streamSettings":{"network":"tcp","security":"none"}}]}
EOF
	fi
	if "$binary" -test -config "$probe/config.json" >"$probe/result" 2>&1; then
		return 0
	else
		rc=$?
		head -c 8192 "$probe/result" >&2
		log "ОШИБКА: пакет Xray несовместим с текущим транспортом VLESS reverse (security=$(uci_get security none), rc=$rc). Нужна сборка с поддержкой текущего транспорта; рабочий бинарник и кэш сохранены"
		return "$rc"
	fi
)

render_client_config() (
    local tachyon_port
    tachyon_port="$(tachyon_tunnel_port)"
	local temp_dir rc xray_host out stdout router_id vps_host vps_port uuid ssh_uuid encryption flow reverse_tag ssh_reverse_tag admin_host admin_port ssh_host ssh_port xray_config xray_config_dir
	temp_dir=""
	out=""
	trap 'rm -f "$out"; [ -z "$temp_dir" ] || rmdir "$temp_dir" 2>/dev/null || true' EXIT
	trap 'exit 1' INT TERM
	umask 077
	stdout="0"
	if [ "${1:-}" = "--stdout" ]; then
		stdout="1"
	fi

	router_id="$(safe_id "$(uci_get router_id main)")"
	vps_host="$(uci_get vps_host '')"
	local wan_sockopt wan_xray_device
	wan_sockopt=''
	if truthy "$(uci_get wan_direct 0)"; then
		command -v wan_prepare >/dev/null 2>&1 || die "WAN helper missing: $WAN_HELPER"
		wan_prepare || die "не удалось подготовить прямое соединение через WAN"
		vps_host="$(wan_resolve_host "$vps_host")" || die "VPS host не разрешается через WAN DNS"
		wan_xray_device="$(wan_device)" || die "выбранный WAN интерфейс отключился"
		wan_sockopt=", \"sockopt\": {\"mark\": $((PODKOP_BYPASS_MARK)), \"interface\": \"$(json_escape "$wan_xray_device")\"}"
	fi
	vps_port="$(xray_port vps_port "$(uci_get vps_port 8443)")" || return 1
	uuid="$(uci_get vless_uuid '')"
	ssh_uuid="$(uci_get ssh_vless_uuid '')"
	encryption="$(uci_get vless_encryption none)"
	flow="$(uci_get vless_flow '')"
	security="$(uci_get security none)"
	reality_pk="$(uci_get reality_public_key '')"
	reality_sid="$(uci_get reality_short_id '')"
	reality_sni="$(uci_get reality_server_name '')"
	reality_fp="$(uci_get reality_fingerprint chrome)"
	tls_sni="$(uci_get tls_sni '')"
	tls_pin="$(uci_get tls_pin '')"
	reverse_tag="$(uci_get reverse_tag reverse-in)"
	ssh_reverse_tag="$(uci_get ssh_reverse_tag "${reverse_tag}-ssh")"
	admin_host="$(uci_get admin_host 127.0.0.1)"
	admin_port="$(xray_port admin_port "$(uci_get admin_port 80)")" || return 1
	ssh_host="$(uci_get ssh_host 127.0.0.1)"
	ssh_port="$(xray_port ssh_port "$(uci_get ssh_port 22)")" || return 1
	xray_config="$(uci_get xray_config /etc/xray/owrt-remote-client.json)"

	[ -n "$vps_host" ] || die "vps_host пустой"
	[ -n "$uuid" ] || die "vless_uuid пустой"
	[ -n "$ssh_uuid" ] || ssh_uuid="$uuid"
	xray_valid_uuid "$uuid" || die "vless_uuid: ожидается UUID в формате 8-4-4-4-12; значение не исправляется автоматически"
	xray_valid_uuid "$ssh_uuid" || die "ssh_vless_uuid: ожидается UUID в формате 8-4-4-4-12; значение не исправляется автоматически"
	[ -z "$(uci_get ssh_vless_uuid '')" ] || [ "$uuid" != "$ssh_uuid" ] || die "vless_uuid и ssh_vless_uuid должны различаться для двух reverse-туннелей"
	xray_valid_tag reverse_tag "$reverse_tag" || return 1
	xray_valid_tag ssh_reverse_tag "$ssh_reverse_tag" || return 1
	[ "$reverse_tag" != "$ssh_reverse_tag" ] || die "reverse_tag и ssh_reverse_tag должны различаться"
	for xray_host in "$vps_host" "$admin_host" "$ssh_host"; do
		[ -n "$xray_host" ] || die "VPS/admin/SSH host пустой"
		if [ "$(printf '%s' "$xray_host" | LC_ALL=C tr -d '\001-\040\177')" != "$xray_host" ]; then
			die "VPS/admin/SSH host содержит пробел или управляющий символ"
		fi
	done
	case "$vps_host" in *://*|*/*) die "vps_host должен содержать IP или домен без http(s):// и пути" ;; esac
	case "$security" in none|reality|tls) ;; *) die "security: ожидается none, reality или tls" ;; esac
	if [ "$security" = tls ]; then
		case "$tls_sni" in ''|*://*) die "tls_sni: SNI-домен хаба без схемы и путей" ;; esac
		if [ "$(printf '%s' "$tls_sni" | LC_ALL=C tr -d '\001-\040\177')" != "$tls_sni" ]; then
			die "tls_sni: содержит пробел или управляющий символ"
		fi
		case "$tls_pin" in *[!0-9a-fA-F]*|'') die "tls_pin: 64-символьный hex SHA256 сертификата хаба из карточки роутера на VPS" ;; esac
		[ "${#tls_pin}" -eq 64 ] || die "tls_pin: длина SHA256 должна быть 64 hex-символа"
		transport_stream='"security": "tls",
        "tlsSettings": {"serverName": "'"$(json_escape "$tls_sni")"'", "pinnedPeerCertSha256": "'"$(json_escape "$tls_pin")"'", "alpn": ["h2", "http/1.1"], "fingerprint": "'"$(json_escape "$reality_fp")"'"}'
	elif [ "$security" = reality ]; then
		case "$reality_pk" in ''|*[!A-Za-z0-9_-]*) die "reality_public_key: ожидается 43-символьный base64url-ключ X25519 из карточки роутера на VPS" ;; esac
		[ "${#reality_pk}" -eq 43 ] || die "reality_public_key: длина ключа X25519 должна быть 43 символа"
		case "$reality_sni" in ''|*://*) die "reality_server_name: укажите camouflage-домен без схемы и путей (например www.microsoft.com)" ;; esac
		if [ "$(printf '%s' "$reality_sni" | LC_ALL=C tr -d '\001-\040\177')" != "$reality_sni" ]; then
			die "reality_server_name: содержит пробел или управляющий символ"
		fi
		case "$reality_fp" in ''|*[!a-zA-Z0-9_-]*) die "reality_fingerprint: ожидается отпечаток без пробелов (chrome, firefox, safari, ios, android)" ;; esac
		case "$reality_sid" in *[!0-9a-fA-F]*) die "reality_short_id: ожидается hex (0-9a-f)" ;; esac
		transport_stream='"security": "reality",
        "realitySettings": {"show": false, "fingerprint": "'"$(json_escape "$reality_fp")"'", "serverName": "'"$(json_escape "$reality_sni")"'", "publicKey": "'"$(json_escape "$reality_pk")"'", "shortId": "'"$(json_escape "$reality_sid")"'"}'
	else
		transport_stream='"security": "none"'
	fi

	if [ "$stdout" = "1" ]; then
		xray_config_dir="${TMPDIR:-/tmp}"
	else
		xray_config_dir="$(dirname "$xray_config")"
		mkdir -p "$xray_config_dir" || return 1
	fi
	temp_dir="$(mktemp -d "$xray_config_dir/.owrt-remote-client.XXXXXX")" || return 1
	# Xray detects JSON by extension; keep the candidate private and on the
	# same filesystem as the destination so the final rename is atomic.
	out="$temp_dir/config.json"
	# Freedom denies VLESS reverse by default in newer cores. Each redirect
	# fixes its destination before finalRules; allow only that service's TCP port.
	cat >"$out" <<EOF
{
  "log": {
    "access": "none",
    "error": "",
    "loglevel": "warning"
  },
  "inbounds": [],
  "outbounds": [
    $([ "$tachyon_port" = 0 ] || printf '{"tag":"router-tachyon","protocol":"freedom","settings":{"redirect":"127.0.0.1:%s","finalRules":[{"action":"allow","network":"tcp","port":%s}]}},' "$tachyon_port" "$tachyon_port")
    {
      "tag": "router-admin",
      "protocol": "freedom",
      "settings": {
        "redirect": "$(json_escape "$admin_host"):$admin_port",
        "finalRules": [{"action": "allow", "network": "tcp", "port": $admin_port}]
      }
    },
    {
      "tag": "router-ssh",
      "protocol": "freedom",
      "settings": {
        "redirect": "$(json_escape "$ssh_host"):$ssh_port",
        "finalRules": [{"action": "allow", "network": "tcp", "port": $ssh_port}]
      }
    },
    {
      "tag": "vps-interconn",
      "protocol": "vless",
      "settings": {
        "address": "$(json_escape "$vps_host")",
        "port": $vps_port,
        "id": "$(json_escape "$uuid")",
        "encryption": "$(json_escape "$encryption")",
        "flow": "$(json_escape "$flow")",
        "reverse": {
          "tag": "$(json_escape "$reverse_tag")"
        }
      },
      "streamSettings": {
        "network": "tcp",
        $transport_stream$wan_sockopt
      }
    },
    {
      "tag": "vps-ssh-interconn",
      "protocol": "vless",
      "settings": {
        "address": "$(json_escape "$vps_host")",
        "port": $vps_port,
        "id": "$(json_escape "$ssh_uuid")",
        "encryption": "$(json_escape "$encryption")",
        "flow": "$(json_escape "$flow")",
        "reverse": {
          "tag": "$(json_escape "$ssh_reverse_tag")"
        }
      },
      "streamSettings": {
        "network": "tcp",
        $transport_stream$wan_sockopt
      }
    }
  ],
  "routing": {
    "rules": [
      $([ "$tachyon_port" = 0 ] || printf '{"type":"field","inboundTag":["%s"],"ip":["127.0.0.1"],"port":%s,"outboundTag":"router-tachyon"},' "$(json_escape "$reverse_tag")" "$tachyon_port")
      {
        "type": "field",
        "inboundTag": [
          "$(json_escape "$reverse_tag")"
        ],
        "outboundTag": "router-admin"
      },
      {
        "type": "field",
        "inboundTag": [
          "$(json_escape "$ssh_reverse_tag")"
        ],
        "outboundTag": "router-ssh"
      }
    ]
  },
  "remarks": "OpenWrt Remote client for $(json_escape "$router_id")"
}
EOF
	rc=$?
	[ "$rc" = 0 ] || return "$rc"
	chmod 0600 "$out" || return 1

	if [ "$stdout" = "1" ]; then
		cat "$out"
		return
	fi

	ensure_xray_available >&2 || return 1
	validate_xray_config "$out" || return $?
	mv -f "$out" "$xray_config" || return 1
	printf '%s\n' "$xray_config"
)

heartbeat_json() {
	local router_id router_name role public_url hub_url xray_state service_state ssh_state event heartbeat_interval
	event="${1:-}"
	router_id="$(safe_id "$(uci_get router_id main)")"
	router_name="$(uci_get router_name "$router_id")"
	role="$(uci_get role node)"
	public_url="$(uci_get public_url '')"
	hub_url="$(uci_get hub_url '')"
	heartbeat_interval="$(safe_num "$(uci_get heartbeat_interval 30)" 30)"
	[ "$heartbeat_interval" -lt 10 ] && heartbeat_interval=10

	if xray_running; then
		xray_state="running"
	else
		xray_state="stopped"
	fi
	if service_enabled; then
		service_state="enabled"
	else
		service_state="disabled"
	fi
	if ssh_running; then
		ssh_state="running"
	else
		ssh_state="stopped"
	fi

	cat <<EOF
{
  "id": $(json_string "$router_id"),
  "name": $(json_string "$router_name"),
  "role": $(json_string "$role"),
  "model": $(json_string "$(host_model)"),
  "board": $(json_string "$(board_name)"),
  "release": $(json_string "$(release_text)"),
  "hostname": $(json_string "$(hostname 2>/dev/null || printf openwrt)"),
  "public_url": $(json_string "$public_url"),
  "admin_host": $(json_string "$(uci_get admin_host 127.0.0.1)"),
  "admin_port": $(safe_num "$(uci_get admin_port 80)" 80),
  "ssh_host": $(json_string "$(uci_get ssh_host 127.0.0.1)"),
  "ssh_port": $(safe_num "$(uci_get ssh_port 22)" 22),
  "hub_url": $(json_string "$hub_url"),
  "vps_host": $(json_string "$(uci_get vps_host '')"),
  "vps_host_mode": $(json_string "$(vps_host_mode)"),
  "wan_direct": $(json_string "$(uci_get wan_direct 0)"),
  "heartbeat_interval": $heartbeat_interval,
  "uptime": $(safe_num "$(uptime_seconds)" 0),
  "load": $(json_string "$(load_text)"),
  "memory": $(json_string "$(memory_text)"),
  "flash": $(json_string "$(flash_text)"),
  "temperature": $(json_string "$(temperature_text)"),
  "xray": $(json_string "$xray_state"),
  "xray_control": $([ -r "$CONTROL_HELPER" ] && printf 1 || printf 0),
  "xray_control_result": $(xray_control_result_json || printf null),
  "ssh": $(json_string "$ssh_state"),
  "tachyon": $(tachyon_json),
  "event": $(json_string "$event"),
  "service": $(json_string "$service_state")
}
EOF
}

remote_clock_ms() {
	LC_ALL=C awk '{ printf "%.0f", $1 * 1000; exit }' /proc/uptime 2>/dev/null || date +%s000
}

remote_url_origin() {
	# Return only a validated origin, never userinfo, path, query or fragment.
	printf '%s\n' "$1" | LC_ALL=C awk '
		NR != 1 { bad=1 }
		NR == 1 {
			if ($0 ~ /[\001-\040\177]/ || $0 !~ /^https?:\/\//) { bad=1; next }
			scheme=$0; sub(/:.*/, "", scheme)
			authority=$0; sub(/^https?:\/\//, "", authority); sub(/[\/?#].*/, "", authority)
			if (authority ~ /@/) { bad=1; next }
			port=(scheme == "https" ? 443 : 80)
			if (authority ~ /^\[[0-9a-fA-F:]+\](:[0-9]+)?$/) {
				host=authority; sub(/\].*/, "]", host)
				if (authority ~ /\]:/) { port=authority; sub(/^.*\]:/, "", port) }
			} else if (authority ~ /^[a-zA-Z0-9_.-]+(:[0-9]+)?$/) {
				host=authority; sub(/:.*/, "", host)
				if (authority ~ /:/) { port=authority; sub(/^.*:/, "", port) }
			} else { bad=1; next }
			if (port + 0 < 1 || port + 0 > 65535) { bad=1; next }
		}
		END { if (bad || !host) exit 1; printf "%s://%s:%d", scheme, tolower(host), port + 0 }
	'
}

remote_curl_metrics() {
	[ -n "${OWRT_REMOTE_HTTP_METRICS:-}" ] || return 0
	# Parse numeric fields only. redirect_url may contain secrets and is excluded.
	LC_ALL=C awk -v secure="$2" -v resolver="$3" -v hop="$4" -v wan_dns="${5:-}" -v source="${6:-curl}" '
		NF >= 6 && $1 ~ /^[0-9][0-9][0-9]$/ {
			for (i=2; i<=6; i++) if ($i !~ /^[0-9]+(\.[0-9]+)?$/) exit
			dns=sprintf("%.1f", $2*1000); tcp=($3>0 ? sprintf("%.1f", ($3>$2 ? ($3-$2)*1000 : 0)) : "incomplete")
			if (source != "curl") dns=(wan_dns ~ /^[0-9]+$/ ? sprintf("%.1f", wan_dns+0) : "n/a")
			if (source !~ /^(curl|lookup|cache|literal|pinned|pre_resolved)$/) source="pre_resolved"
			tls=(secure == "https" ? ($4>0 ? sprintf("%.1f", ($4>$3 ? ($4-$3)*1000 : 0)) : "incomplete") : "n/a")
			printf "tool=curl HTTP=%s DNS_ms=%s TCP_ms=%s TLS_ms=%s TTFB_ms=%.1f total_ms=%.1f WAN_resolve_ms=%d hop=%d DNS_source=%s\n", $1, dns, tcp, tls, $5*1000, $6*1000, resolver, hop, source
			exit
		}' "$1" >>"$OWRT_REMOTE_HTTP_METRICS"
}

remote_curl_post() (
	local url token file mode dir rc hop origin next_origin redirect code dns tcp tls first total target device resolve started remaining resolver_started resolver_ms dns_ms dns_source OWRT_REMOTE_DNS_STATS_FILE
	url="$1"; token="$2"; file="$3"; mode="${4:-normal}"
	origin="$(remote_url_origin "$url")" || return 3
	dir="$(mktemp -d "${TMPDIR:-/tmp}/owrt-remote-http.XXXXXX")" || return 1
	chmod 700 "$dir"
	trap 'rm -f "$dir/body" "$dir/stats" "$dir/error" "$dir/dns"; rmdir "$dir" 2>/dev/null || true' EXIT
	trap 'exit 1' INT TERM
	started="$(remote_clock_ms)"; hop=0
	while :; do
		resolver_ms=0; dns_ms=''; dns_source=curl
		set -- -q -fsS --connect-timeout 4 --noproxy '*' --proto '=http,https'
		if [ "$mode" = wan ]; then
			OWRT_REMOTE_DNS_STATS_FILE="$dir/dns"; : >"$dir/dns"
			dns_source=pre_resolved
			resolver_started="$(remote_clock_ms)"
			target="$(wan_http_target "$url")" || return 1
			resolver_ms=$(( $(remote_clock_ms) - resolver_started ))
			read -r dns_ms dns_source <"$dir/dns" || true
			device="${target%%|*}"; resolve="${target#*|}"
			set -- "$@" --interface "$device" --resolve "$resolve"
		fi
		remaining=$((10000 - $(remote_clock_ms) + started))
		[ "$remaining" -gt 0 ] || return 28
		remaining="$(LC_ALL=C awk -v value="$remaining" 'BEGIN { printf "%.3f", value/1000 }')"
		rc=0
		# Each permitted redirect is a separate authenticated POST. curl -L
		# drops Bearer auth on an origin change, including HTTP -> HTTPS.
		curl "$@" --max-time "$remaining" -o "$dir/body" \
			-w '%{http_code} %{time_namelookup} %{time_connect} %{time_appconnect} %{time_starttransfer} %{time_total} %{redirect_url}\n' \
			-H "Authorization: Bearer $token" -H 'Content-Type: application/json' \
			--data-binary "@$file" "$url" >"$dir/stats" 2>"$dir/error" || rc=$?
		remote_curl_metrics "$dir/stats" "${url%%:*}" "$resolver_ms" "$hop" "$dns_ms" "$dns_source"
		if [ "$rc" != 0 ]; then cat "$dir/error" >&2; return "$rc"; fi
		code=''; redirect=''
		read -r code dns tcp tls first total redirect <"$dir/stats" || true
		redirect="${redirect%"$(printf '\r')"}"
		case "$code" in
			301|302|303|307|308)
				[ -n "$redirect" ] && [ "$hop" -lt 3 ] || return 47
				next_origin="$(remote_url_origin "$redirect")" || return 47
				# Send credentials only within the same origin or to HTTPS on
				# the very same host. Never trust arbitrary redirect destinations.
				if [ "$origin" != "$next_origin" ]; then
					case "$origin|$next_origin" in
						http://*'|'https://*)
							# Compare hosts independently of the two ports.
							target="${next_origin%:*}"
							[ "${origin%:*}" = "http://${target#https://}" ] || return 47
							;;
						*) return 47 ;;
					esac
				fi
				url="$redirect"; origin="$next_origin"; hop=$((hop+1))
				;;
			*) [ ! -f "$dir/body" ] || cat "$dir/body"; return 0 ;;
		esac
	done
)

post_json() (
	local url token file
	url="$1"
	token="$2"
	file="$3"
	# uclient treats an empty *_proxy env value as a proxy URL, then fails
	# to allocate its client for that empty URL. Remove variables entirely.
	unset http_proxy https_proxy HTTP_PROXY HTTPS_PROXY ALL_PROXY all_proxy
	if truthy "$(uci_get wan_direct 0)"; then
		wan_post_json "$url" "$token" "$file"
		return
	fi

	if command -v curl >/dev/null 2>&1; then
		remote_curl_post "$url" "$token" "$file"
		return
	fi
	[ -z "${OWRT_REMOTE_HTTP_METRICS:-}" ] || printf 'tool=uclient/wget DNS_ms=n/a TCP_ms=n/a TLS_ms=n/a\n' >>"$OWRT_REMOTE_HTTP_METRICS"
	if command -v wget >/dev/null 2>&1; then
		wget -q -T 10 -O - \
			--header="Authorization: Bearer $token" \
			--header="Content-Type: application/json" \
			--post-file="$file" "$url"
		return
	fi
	if command -v uclient-fetch >/dev/null 2>&1; then
		uclient-fetch -q -T 10 -O - \
			--header="Authorization: Bearer $token" \
			--header="Content-Type: application/json" \
			--post-file="$file" "$url"
		return
	fi
	die "для heartbeat нужен uclient-fetch, wget или curl"
)

log_post_json_bounded() (
	# Also bounds remote_curl_post's private response body. The subshell limit
	# cannot affect heartbeat/Xray. POSIX -f uses 512-byte blocks (32 KiB here).
	ulimit -f 64 || exit 1
	post_json "$1" "$2" "$3"
)

global_logs_state() {
	local enabled xray
	enabled=false; xray=stopped
	truthy "$(uci_get enabled 0)" && enabled=true
	xray_running && xray=running
	printf '{"enabled":%s,"xray":"%s"}' "$enabled" "$xray"
}

sync_global_logs() (
	local helper router_id file response endpoint base token journal offset clear_token rc sync_lock owner attempt runtime TMPDIR stale
	helper="${OWRT_REMOTE_LOG_HELPER:-/usr/lib/owrt-remote/logs.sh}"
	[ -r "$helper" ] || return 0
	token="$(uci_get hub_token '')"; [ -n "$token" ] || return 0
	# The journal is independent of Remote's enabled flag and Xray lifecycle.
	sh "$helper" check || return 1
	runtime="${OWRT_REMOTE_LOG_RUNTIME:-/tmp/owrt-remote-log-runtime}"
	# Older helpers create only their journal directory. An independent agent
	# update still needs a private runtime directory for delivery and its lock.
	(umask 077; mkdir -p "$runtime") || return 1
	sync_lock="$runtime/sync-lock"
	if ! mkdir "$sync_lock" 2>/dev/null; then
		# Give a sender time to write its PID, then recover an abandoned lock.
		for attempt in 1 2 3 4 5 6 7 8 9 10; do
			owner="$(cat "$sync_lock/pid" 2>/dev/null)"
			case "$owner" in ''|*[!0-9]*) sleep 0.1 ;; *) break ;; esac
		done
		owner="$(cat "$sync_lock/pid" 2>/dev/null)"
		case "$owner" in ''|*[!0-9]*) ;; *) kill -0 "$owner" 2>/dev/null && return 0 ;; esac
		if ! mkdir "$sync_lock/reap" 2>/dev/null; then
			owner="$(cat "$sync_lock/reap/pid" 2>/dev/null)"
			case "$owner" in ''|*[!0-9]*) sleep 1 ;; *) kill -0 "$owner" 2>/dev/null && return 0 ;; esac
			rm -f "$sync_lock/reap/pid"; rmdir "$sync_lock/reap" 2>/dev/null || return 0
			return 0
		fi
		printf '%s\n' "$$" >"$sync_lock/reap/pid"
		owner="$(cat "$sync_lock/pid" 2>/dev/null)"
		case "$owner" in ''|*[!0-9]*) ;; *) if kill -0 "$owner" 2>/dev/null; then rm -f "$sync_lock/reap/pid"; rmdir "$sync_lock/reap"; return 0; fi ;; esac
		rm -f "$sync_lock/pid"
		rm -f "$sync_lock/reap/pid"
		rmdir "$sync_lock/reap" || return 0
		rmdir "$sync_lock" 2>/dev/null || return 0
		mkdir "$sync_lock" 2>/dev/null || return 0
	fi
	# ash keeps $$ unchanged inside a subshell. Store the actual sender PID so
	# a killed sender is recoverable while its parent service is still alive.
	if read -r owner attempt </proc/self/stat 2>/dev/null; then
		printf '%s\n' "$owner" >"$sync_lock/pid"
	else
		printf '%s\n' "$$" >"$sync_lock/pid"
	fi
	file=''; response=''
	trap 'rm -f "$file" "$response" "$sync_lock/pid"; rmdir "$sync_lock" 2>/dev/null || true' EXIT
	trap 'exit 1' INT TERM
	# A killed sender can leave one bounded payload; reclaim it under the singleton.
	rm -f "$runtime"/sync.*
	# Give this sender its own temporary HTTP directory; never sweep heartbeat's
	# files. Clean a curl subprocess killed before its EXIT trap could run.
	TMPDIR="$runtime/http"; export TMPDIR
	mkdir -p "$TMPDIR" || return 1
	for stale in "$TMPDIR"/owrt-remote-http.*; do
		[ -d "$stale" ] || continue
		rm -f "$stale/body" "$stale/stats" "$stale/error" "$stale/dns"
		rmdir "$stale" 2>/dev/null || true
	done
	if truthy "$(uci_get wan_direct 0)" && [ ! -s "$WAN_STATE/active-interface" ]; then wan_prepare || return 1; fi
	router_id="$(safe_id "$(uci_get router_id main)")"
	# Export at most 16 KiB of raw records directly into a bounded request file.
	# Neither the Flash journal nor a base64 packet is copied into a shell variable.
	umask 077
	file="$runtime/sync.$$"; response="$file.response"
	{
		printf '{"id":%s,"batch":' "$(json_string "$router_id")"
		sh "$helper" export || exit 1
		printf ',"state":%s}\n' "$(global_logs_state)"
	} >"$file" || return 1
	for endpoint in $(heartbeat_candidate_endpoints); do
		base="$(heartbeat_base_from_endpoint "$endpoint")"
		if log_post_json_bounded "$base/api/router-logs" "$token" "$file" >"$response" 2>/dev/null &&
			grep -Eq '"ok"[[:space:]]*:[[:space:]]*true' "$response"; then
			journal="$(jsonfilter -i "$response" -e '@.journal_id' 2>/dev/null)"
			offset="$(jsonfilter -i "$response" -e '@.offset' 2>/dev/null)"
			clear_token="$(jsonfilter -i "$response" -e '@.clear_request' 2>/dev/null)"
			sh "$helper" ack "$journal" "$offset" "$clear_token"
			rc=$?
			rm -f "$file" "$response"
			rm -f "$sync_lock/pid"; rmdir "$sync_lock" 2>/dev/null || true
			trap - EXIT INT TERM
			return "$rc"
		fi
	done
	rm -f "$file" "$response"
	rm -f "$sync_lock/pid"; rmdir "$sync_lock" 2>/dev/null || true
	trap - EXIT INT TERM
	return 1
)

heartbeat_base_from_endpoint() {
	printf '%s' "${1%/api/heartbeat}"
}

heartbeat_emit_endpoint() {
	local base marker
	base="$(normalize_url_base "$1")"
	[ -n "$base" ] || return 0
	case "${HEARTBEAT_REQUIRE_HTTPS:-0}|$base" in 1'|'http://*) return 0 ;; esac
	marker="|$base|"
	case "${HEARTBEAT_ENDPOINT_SEEN:-}" in
		*"$marker"*) return 0 ;;
	esac
	HEARTBEAT_ENDPOINT_SEEN="${HEARTBEAT_ENDPOINT_SEEN:-}$marker"
	printf '%s/api/heartbeat\n' "$base"
}

heartbeat_candidate_endpoints() {
	local hub_url public_url vps_host HEARTBEAT_REQUIRE_HTTPS
	HEARTBEAT_ENDPOINT_SEEN='|'
	hub_url="$(uci_get hub_url '')"
	public_url="$(uci_get public_url '')"
	vps_host="$(uci_get vps_host '')"
	HEARTBEAT_REQUIRE_HTTPS=0
	case "$hub_url" in https://*) HEARTBEAT_REQUIRE_HTTPS=1 ;; esac
	heartbeat_emit_endpoint "$hub_url"
	heartbeat_emit_endpoint "$public_url"
	case "$vps_host" in
		'')
			;;
		http://*|https://*)
			heartbeat_emit_endpoint "$vps_host"
			;;
		*)
			heartbeat_emit_endpoint "https://$vps_host"
			heartbeat_emit_endpoint "http://$vps_host"
			heartbeat_emit_endpoint "http://$vps_host:8088"
			;;
	esac
}

heartbeat_set_url_if_changed() {
	local key next current ignored_file ignored
	key="$1"
	next="$2"
	case "$next" in http://?*|https://?*) ;; *) return 1 ;; esac
	current="$(uci_get "$key" '')"
	case "$current|$next" in
		https://*'|'http://*)
			ignored_file="${TMPDIR:-/tmp}/owrt-remote-$key-ignored"
			ignored="$current|$next"
			if [ "$(cat "$ignored_file" 2>/dev/null)" != "$ignored" ]; then
				log "heartbeat kept $key: current=$current proposed=$next reason=https-downgrade"
				printf '%s' "$ignored" >"$ignored_file"
			fi
			return 1
			;;
	esac
	uci_set_if_changed "$key" "$next"
}

heartbeat_apply_hub_update() {
	local response_file fallback_base next_hub_url next_public_url next_vps_host changed old_vps_host mode ignored_file ignored
	response_file="$1"
	fallback_base="$2"
	next_hub_url="$(json_extract_object_string "$response_file" hub_update hub_url)"
	next_public_url="$(json_extract_object_string "$response_file" hub_update public_url)"
	next_vps_host="$(json_extract_object_string "$response_file" hub_update vps_host)"
	old_vps_host="$(uci_get vps_host '')"
	mode="$(vps_host_mode)"
	# A fallback is a temporary transport, not a new configured Hub URL.
	if [ -z "$next_hub_url" ] && [ -z "$(uci_get hub_url '')" ]; then
		next_hub_url="$fallback_base"
	fi
	changed=0
	if heartbeat_set_url_if_changed hub_url "$next_hub_url"; then
		changed=1
	fi
	if heartbeat_set_url_if_changed public_url "$next_public_url"; then
		changed=1
	fi
	if [ "$mode" = auto ]; then
		if uci_set_if_changed vps_host "$next_vps_host"; then
			changed=1
		fi
	elif [ -n "$next_vps_host" ] && [ "$old_vps_host" != "$next_vps_host" ]; then
		ignored_file="${TMPDIR:-/tmp}/owrt-remote-vps-host-ignored"
		ignored="$old_vps_host|$next_vps_host"
		if [ "$(cat "$ignored_file" 2>/dev/null)" != "$ignored" ]; then
			log "heartbeat kept vps_host: current=$old_vps_host proposed=$next_vps_host reason=manual"
			printf '%s' "$ignored" >"$ignored_file"
		fi
	fi
	[ "$changed" = "1" ] || return 0
	uci commit "$CONFIG" >/dev/null 2>&1 || return 1
	log "heartbeat updated hub settings: hub_url=$(uci_get hub_url '') public_url=$(uci_get public_url '') vps_host=$(uci_get vps_host '')"
	if [ "$mode" = auto ] && [ -n "$next_vps_host" ] && [ "$old_vps_host" != "$next_vps_host" ]; then
		log "heartbeat updated vps_host: old=$old_vps_host new=$next_vps_host reason=hub_update mode=auto"
		# The running Xray keeps its old address until it is restarted.
		( sleep 2; /etc/init.d/owrt-remote restart >/dev/null 2>&1 ) </dev/null >/dev/null 2>&1 &
	fi
}

heartbeat_failure_reason() {
	case "$1|$2" in
		*'|'401|*'|'403) printf auth_rejected ;;
		28'|'*) printf timeout ;;
		5'|'*|6'|'*) printf dns_failed ;;
		7'|'*) printf connect_failed ;;
		35'|'*) printf tls_handshake_failed ;;
		51'|'*|58'|'*|60'|'*|77'|'*) printf tls_verification_failed ;;
		47'|'*) printf redirect_rejected ;;
		*'|'408|*'|'429|*'|'500|*'|'502|*'|'503|*'|'504) printf server_temporary ;;
		18'|'*|52'|'*|55'|'*|56'|'*|92'|'*) printf connection_interrupted ;;
		0'|'*) printf invalid_heartbeat_response ;;
		*) printf request_failed ;;
	esac
}

heartbeat_diagnostics() {
	local state
	state="${TMPDIR:-/tmp}/owrt-remote-heartbeat-last"
	printf 'Последний Heartbeat (только безопасные поля):\n'
	if [ -r "$state" ]; then cat "$state"; else printf 'Замеров пока нет; выполни owrt-remote heartbeat.\n'; fi
}

send_heartbeat() {
	local hub_url token endpoint tmp response event used fallback_base errors rc dir metrics http attempt max_attempts reason previous previous_reason safe_endpoint elapsed started diagnostic
	(
	event="${1:-}"
	hub_url="$(uci_get hub_url '')"
	token="$(uci_get hub_token '')"
	[ -n "$hub_url" ] || die "hub_url пустой"
	[ -n "$token" ] || die "hub_token пустой"
	if truthy "$(uci_get wan_direct 0)"; then
		command -v wan_prepare >/dev/null 2>&1 || die "WAN helper missing: $WAN_HELPER"
		wan_prepare || { log 'Heartbeat: не удалось подготовить прямой WAN'; return 1; }
		wan_reconcile_xray
	fi

	dir="$(mktemp -d "${TMPDIR:-/tmp}/owrt-remote-heartbeat.XXXXXX")" || return 1
	chmod 700 "$dir"
	trap 'rm -f "$dir/payload" "$dir/response" "$dir/response.error" "$dir/metrics" "$dir/last"; rmdir "$dir" 2>/dev/null || true' EXIT
	trap 'exit 1' INT TERM
	tmp="$dir/payload"; response="$dir/response"
	errors="$response.error"
	metrics="$dir/metrics"
	export OWRT_REMOTE_HTTP_METRICS="$metrics"
	heartbeat_json "$event" >"$tmp"
	used=0
	previous=''; previous_reason=''
	for endpoint in $(heartbeat_candidate_endpoints); do
		used=1
		safe_endpoint="$(remote_url_origin "$endpoint")" || { log 'Heartbeat: ошибка; reason=invalid_endpoint'; continue; }
		if [ -n "$previous" ]; then
			log "Heartbeat: fallback; from=$previous; to=$safe_endpoint; reason=$previous_reason; предыдущие попытки исчерпаны"
		fi
		attempt=1; max_attempts=1
		case "$endpoint" in https://*) max_attempts=2 ;; esac
		while [ "$attempt" -le "$max_attempts" ]; do
			rc=0; : >"$metrics"; started="$(remote_clock_ms)"
			post_json "$endpoint" "$token" "$tmp" >"$response" 2>"$errors" || rc=$?
			elapsed=$(( $(remote_clock_ms) - started ))
			http="$(sed -n 's/.*HTTP=\([0-9][0-9][0-9]\).*/\1/p' "$metrics" | tail -n 1)"
			reason="$(heartbeat_failure_reason "$rc" "$http")"
			if grep -Fq 'Failed to allocate uclient context' "$errors"; then reason=http_client_context_failed; fi
			diagnostic="endpoint=$safe_endpoint; attempt=$attempt/$max_attempts; rc=$rc; reason=$reason; elapsed_ms=$elapsed; $(tail -n 1 "$metrics")"
			printf '%s\n' "$diagnostic" >"$dir/last"
			mv -f "$dir/last" "${TMPDIR:-/tmp}/owrt-remote-heartbeat-last"
			if [ "$rc" = 0 ] && grep -Eq '"ok"[[:space:]]*:[[:space:]]*true' "$response"; then
				fallback_base="$(heartbeat_base_from_endpoint "$endpoint")"
				if ! heartbeat_apply_hub_update "$response" "$fallback_base"; then
					log 'Heartbeat: Hub ответил, но обновление настроек не применилось'
					return 1
				fi
				# Stable OK messages remain deduplicated by the RAM journal;
				# fresh timings are available separately in network-diagnostics.
				printf '%s\n' "endpoint=$safe_endpoint; attempt=$attempt/$max_attempts; rc=0; reason=ok; elapsed_ms=$elapsed; $(tail -n 1 "$metrics")" >"$dir/last"
				mv -f "$dir/last" "${TMPDIR:-/tmp}/owrt-remote-heartbeat-last"
				cat "$response"
				xray_control_dispatch "$response" || log 'Remote Xray: команда не принята; повторная доставка при следующем Heartbeat'
				tachyon_reconcile_xray || log 'Tachyon: обновление маршрута отложено'
				log "Heartbeat: OK; Hub=$safe_endpoint; WAN_direct=$(uci_get wan_direct 0); WAN_active=$(cat "$WAN_STATE/active-interface" 2>/dev/null)"
				return 0
			fi
			# Do not log curl stderr or response bodies: either may echo secrets.
			log "Heartbeat: ошибка; $diagnostic"
			[ "$reason" != auth_rejected ] || return 1
			case "$reason" in timeout|dns_failed|connect_failed|tls_handshake_failed|server_temporary|connection_interrupted)
				if [ "$attempt" -lt "$max_attempts" ]; then
					attempt=$((attempt+1))
					log "Heartbeat: retry HTTPS; endpoint=$safe_endpoint; attempt=$attempt/$max_attempts; reason=$reason; delay=1s"
					sleep 1
					continue
				fi ;;
			esac
			break
		done
		previous="$safe_endpoint"; previous_reason="$reason"
	done
	[ "$used" = "1" ] || die "hub_url/public_url/vps_host пустые"
	case "$hub_url" in https://*) log 'Heartbeat: fallback остановлен; reason=https_required; автоматический переход на HTTP отключён' ;; esac
	return 1
	)
}

wan_reconcile_xray() {
	local config bound device
	xray_control_stopped && return 0
	truthy "$(uci_get enabled 0)" || return 0
	device="$(wan_device)" || return 1
	if ! xray_running; then
		wan_recover_xray
		return $?
	fi
	config="$(uci_get xray_config /etc/xray/owrt-remote-client.json)"
	[ -r "$config" ] || return 0
	bound="$(jsonfilter -i "$config" -e '@.outbounds[@.tag="vps-interconn"].streamSettings.sockopt.interface' 2>/dev/null)"
	[ "$bound" != "$device" ] || return 0
	wan_reconnect_xray "$bound" "$device"
}

wan_recover_xray() {
	local lock owner rest state running heartbeat now last attempt
	xray_control_stopped && return 0
	(
	umask 077
	lock="${TMPDIR:-/tmp}/owrt-remote-xray-recovery"
	# A stopped procd instance cannot be revived by sending it a signal.
	# Serialize re-registration; do not interrupt the healthy heartbeat instance.
	attempt=0
	while ! mkdir "$lock" 2>/dev/null; do
		owner="$(cat "$lock/pid" 2>/dev/null)"
		case "$owner" in
			''|*[!0-9]*)
				# Allow a new worker to record its PID before reaping an empty lock.
				if [ "$attempt" -lt 10 ]; then attempt=$((attempt+1)); sleep 0.1; continue; fi ;;
			*) kill -0 "$owner" 2>/dev/null && return 0 ;;
		esac
		wan_recovery_reap "$lock" "$attempt"
		attempt=$((attempt+1)); [ "$attempt" -lt 20 ] || return 0
	done
	trap 'rm -f "$lock/pid"; rmdir "$lock" 2>/dev/null || true' EXIT
	trap 'exit 1' INT TERM
	owner=$$
	# ash keeps $$ unchanged in a subshell; /proc/self identifies this worker.
	if [ -r /proc/self/stat ]; then read -r owner rest </proc/self/stat || owner=$$; fi
	printf '%s\n' "$owner" >"$lock/pid"
	truthy "$(uci_get enabled 0)" || return 0
	wan_select_interface >/dev/null || return 0
	xray_running && return 0
	state="$(ubus call service list '{"name":"owrt-remote"}' 2>/dev/null)" || return 1
	running="$(printf '%s' "$state" | jsonfilter -e '@["owrt-remote"].instances.xray.running' 2>/dev/null)"
	[ "$running" != true ] || return 0
	heartbeat="$(printf '%s' "$state" | jsonfilter -e '@["owrt-remote"].instances.heartbeat.running' 2>/dev/null)"
	# Respect an explicit service stop, including stops made outside the panel.
	[ "$heartbeat" = true ] || return 0
	now="$(uptime_seconds)"
	now="$(safe_num "$now" 0)"
	[ "$now" -gt 0 ] || now="$(safe_num "$(date +%s 2>/dev/null)" 0)"
	last="$(safe_num "$(cat "${TMPDIR:-/tmp}/owrt-remote-xray-recovery.last" 2>/dev/null)" 0)"
	if [ "$last" -gt 0 ] && [ "$now" -ge "$last" ] && [ $((now-last)) -lt 300 ]; then return 0; fi
	printf '%s\n' "$now" >"${TMPDIR:-/tmp}/owrt-remote-xray-recovery.last"
	log 'Xray: WAN доступен, туннель остановлен; запрошен повторный запуск отдельного instance'
	ubus call service add '{"name":"owrt-remote","instances":{"xray":{"command":["/usr/sbin/owrt-remote","run"],"env":{"OWRT_REMOTE_SERVICE_LOG":"1"},"respawn":["3600","5","5"],"stdout":true,"stderr":true}}}' >/dev/null || {
		log 'ОШИБКА: procd не принял запрос восстановления Xray; Heartbeat продолжает работать'
		return 1
	}
	)
}

wan_recovery_reap() {
	local owner reaper rest
	# The reaper itself must be serialized and recoverable after SIGKILL.
	if ! mkdir "$1/reap" 2>/dev/null; then
		reaper="$(cat "$1/reap/pid" 2>/dev/null)"
		case "$reaper" in
			''|*[!0-9]*) [ "$2" -ge 15 ] || return 0 ;;
			*) kill -0 "$reaper" 2>/dev/null && return 0 ;;
		esac
		rm -f "$1/reap/pid"; rmdir "$1/reap" 2>/dev/null || return 0
		return 0
	fi
	reaper=$$
	if [ -r /proc/self/stat ]; then read -r reaper rest </proc/self/stat || reaper=$$; fi
	printf '%s\n' "$reaper" >"$1/reap/pid"
	owner="$(cat "$1/pid" 2>/dev/null)"
	case "$owner" in
		''|*[!0-9]*) ;;
		*) if kill -0 "$owner" 2>/dev/null; then rm -f "$1/reap/pid"; rmdir "$1/reap"; return 0; fi ;;
	esac
	rm -f "$1/pid" "$1/reap/pid"
	rmdir "$1/reap" 2>/dev/null && rmdir "$1" 2>/dev/null || true
}

wan_reconnect_xray() {
	local restart_lock owner
	restart_lock="${TMPDIR:-/tmp}/owrt-remote-wan-restart"
	# A concurrent heartbeat must not enqueue another restart of the same tunnel.
	if ! mkdir "$restart_lock" 2>/dev/null; then
		owner="$(cat "$restart_lock/pid" 2>/dev/null)"
		case "$owner" in ''|*[!0-9]*) return 0 ;; esac
		kill -0 "$owner" 2>/dev/null && return 0
		rm -f "$restart_lock/pid"
		rmdir "$restart_lock" 2>/dev/null || return 0
		mkdir "$restart_lock" 2>/dev/null || return 0
	fi
	log "Reconnecting reverse tunnel after WAN change: $1 -> $2"
	(
		trap 'rm -f "$restart_lock/pid"; rmdir "$restart_lock" 2>/dev/null || true' EXIT
		trap 'exit 1' INT TERM
		sleep 1
		/etc/init.d/owrt-remote restart >/dev/null 2>&1 || log 'WAN failover tunnel restart failed'
	) </dev/null >/dev/null 2>&1 &
	printf '%s' "$!" >"$restart_lock/pid"
}

heartbeat_mark_ok() {
	rm -f "${TMPDIR:-/tmp}/owrt-remote-heartbeat.fail"
}

heartbeat_self_heal() {
	local fail_file restart_file fails now last_restart threshold cooldown
	fail_file="${TMPDIR:-/tmp}/owrt-remote-heartbeat.fail"
	restart_file="${TMPDIR:-/tmp}/owrt-remote-heartbeat.restart"
	threshold=3
	cooldown=300
	now="$(date +%s 2>/dev/null || echo 0)"
	fails=0
	last_restart=0

	[ -f "$fail_file" ] && fails="$(cat "$fail_file" 2>/dev/null || echo 0)"
	fails="$(safe_num "$fails" 0)"
	fails=$((fails + 1))
	printf '%s\n' "$fails" >"$fail_file"

	[ "$fails" -lt "$threshold" ] && return 0
	if truthy "$(uci_get wan_direct 0)" && ! wan_select_interface >/dev/null; then
		log 'Heartbeat: перезапуск отложен; ни один выбранный WAN не имеет физического IPv4 default route'
		return 0
	fi
	if active_ssh_session; then
		log "heartbeat failed ${threshold} times, restart postponed because SSH session is active"
		return 0
	fi
	[ -f "$restart_file" ] && last_restart="$(cat "$restart_file" 2>/dev/null || echo 0)"
	last_restart="$(safe_num "$last_restart" 0)"
	[ $((now - last_restart)) -lt "$cooldown" ] && return 0

	printf '%s\n' "$now" >"$restart_file"
	rm -f "$fail_file"
	log "heartbeat failed ${threshold} times in a row, restarting owrt-remote"
	(
		sleep 1
		/etc/init.d/owrt-remote restart >/dev/null 2>&1
	) &
}

heartbeat_loop() {
	local interval
	interval="$(safe_num "$(uci_get heartbeat_interval 30)" 30)"
	[ "$interval" -lt 10 ] && interval=10
	log "Heartbeat: цикл запущен; интервал=${interval}s"
	while :; do
		if send_heartbeat >/dev/null 2>&1; then
			heartbeat_mark_ok
		else
			heartbeat_self_heal
		fi
		sleep "$interval"
	done
}

status() {
	printf 'router_id: %s\n' "$(uci_get router_id main)"
	printf 'router_name: %s\n' "$(uci_get router_name '')"
	printf 'enabled: %s\n' "$(uci_get enabled 0)"
	printf 'hub_url: %s\n' "$(uci_get hub_url '')"
	printf 'vps_host: %s\n' "$(uci_get vps_host '')"
	printf 'vps_host_mode: %s\n' "$(vps_host_mode)"
	printf 'wan_direct: %s\n' "$(uci_get wan_direct 0)"
	printf 'wan_interfaces: %s\n' "$(uci_get wan_interface wan)"
	printf 'wan_active_interface: %s\n' "$(cat "$WAN_STATE/active-interface" 2>/dev/null)"
	printf 'vps_port: %s\n' "$(uci_get vps_port 8443)"
	printf 'xray_bin: %s\n' "$(xray_bin_path)"
	printf 'xray_config: %s\n' "$(uci_get xray_config /etc/xray/owrt-remote-client.json)"
	if xray_running; then
		printf 'xray_state: running\n'
	else
		printf 'xray_state: stopped\n'
	fi
	if service_enabled; then
		printf 'service: enabled\n'
	else
		printf 'service: disabled\n'
	fi
}

doctor() {
	local ok xray_bin
	ok=1
	ensure_xray_available
	xray_bin="$(xray_bin_path)"

	[ -x "$xray_bin" ] || {
		log "нет Xray: $xray_bin"
		ok=0
	}
	[ -n "$(uci_get hub_url '')" ] || {
		log "hub_url пустой"
		ok=0
	}
	[ -n "$(uci_get hub_token '')" ] || {
		log "hub_token пустой"
		ok=0
	}
	[ -n "$(uci_get vps_host '')" ] || {
		log "vps_host пустой"
		ok=0
	}
	[ -n "$(uci_get vless_uuid '')" ] || {
		log "vless_uuid пустой"
		ok=0
	}

	if [ "$ok" = "1" ]; then
		printf '%s\n' "OK: конфиг выглядит готовым"
	else
		exit 1
	fi
}

# Keep the executable in RAM, but retain one compressed, verified boot copy.
# Cache writes happen only when the executable changes, never per Heartbeat.
xray_runtime_dir() { printf '%s' "${OWRT_REMOTE_XRAY_RUNTIME:-/tmp/owrt-xray}"; }
xray_process_start() { awk '{print $22}' "/proc/$1/stat" 2>/dev/null; }
xray_process_identity() {
	local rest
	read -r XRAY_SELF_PID rest </proc/self/stat || return 1
	XRAY_SELF_BIRTH="$(xray_process_start "$XRAY_SELF_PID")"
	[ -n "$XRAY_SELF_BIRTH" ]
}
xray_bootstrap_lock() {
	local owner attempt current saved
	XRAY_LOCK="$(xray_runtime_dir)/bootstrap-lock"
	mkdir -p "$(xray_runtime_dir)" || return 1
	xray_process_identity || return 1
	attempt=0
	while ! mkdir "$XRAY_LOCK" 2>/dev/null; do
		[ -d "$XRAY_LOCK" ] || return 1
		owner=''; current=''
		read -r owner current <"$XRAY_LOCK/owner" 2>/dev/null || true
		saved="$owner $current"
		case "$owner:$current" in
			*[!0-9:]*|:*|*:) current=''; [ "$attempt" -lt 5 ] || current=stale ;;
			*) [ "$(xray_process_start "$owner")" = "$current" ] || current=stale ;;
		esac
		if [ "$current" = stale ]; then xray_bootstrap_reap "$saved" "$attempt"; fi
		attempt=$((attempt+1)); [ "$attempt" -lt 150 ] || { log 'Xray: загрузчик уже работает; повтор будет выполнен позже'; return 1; }
		sleep 1
	done
	printf '%s %s\n' "$XRAY_SELF_PID" "$XRAY_SELF_BIRTH" >"$XRAY_LOCK/owner" || { rmdir "$XRAY_LOCK" 2>/dev/null || true; return 1; }
}
xray_bootstrap_reap() {
	local owner current saved
	saved="$1"
	if mkdir "$XRAY_LOCK/reap" 2>/dev/null; then
		printf '%s %s\n' "$XRAY_SELF_PID" "$XRAY_SELF_BIRTH" >"$XRAY_LOCK/reap/owner"
		# Re-read after claiming reaping: another waiter may have acquired
		# a new lock since our first observation of the dead process.
		owner=''; current=''; read -r owner current <"$XRAY_LOCK/owner" 2>/dev/null || true
		if [ "$saved" = "$owner $current" ]; then rm -f "$XRAY_LOCK/owner"; fi
		rm -f "$XRAY_LOCK/reap/owner"; rmdir "$XRAY_LOCK/reap"; rmdir "$XRAY_LOCK" 2>/dev/null || true
		return 0
	fi
	# A SIGKILL during reaping must not leave a permanent bootstrap lock.
	owner=''; current=''; read -r owner current <"$XRAY_LOCK/reap/owner" 2>/dev/null || true
	case "$owner:$current" in
		*[!0-9:]*|:*|*:) [ "$2" -ge 10 ] || return 0 ;;
		*) [ "$(xray_process_start "$owner")" != "$current" ] || return 0 ;;
	esac
	rm -f "$XRAY_LOCK/reap/owner"; rmdir "$XRAY_LOCK/reap" 2>/dev/null || true
}
xray_bootstrap_unlock() { rm -f "$XRAY_LOCK/owner"; rmdir "$XRAY_LOCK" 2>/dev/null || true; }
xray_cache_mount() {
	local path
	path="$1"
	while [ ! -e "$path" ]; do path="$(dirname "$path")"; done
	path="$(readlink -f "$path")" || return 1
	awk -v path="$path" '
		(path == $2 || index(path, $2 "/") == 1 || $2 == "/") && length($2) > best {
			best=length($2); mount=$2; fs=$3; flags=$4
		}
		END { if (best) print mount, fs, flags; else exit 1 }
	' /proc/mounts
}
xray_cache_dir() {
	local mount fs flags candidate
	read -r mount fs flags <<EOF
$(xray_cache_mount /overlay)
EOF
	if [ "$mount" = /overlay ]; then
		candidate=/overlay/owrt-remote/xray-cache
	else
		read -r mount fs flags <<EOF
$(xray_cache_mount /)
EOF
		candidate=/etc/owrt-remote/xray-cache
	fi
	case "$fs" in ubifs|jffs2|ext4|ext3|ext2|f2fs|btrfs) ;; *) return 1 ;; esac
	case ",$flags," in *,rw,*) ;; *) return 1 ;; esac
	# Existing symlinks or a nested tmpfs must not redirect this cache into RAM.
	read -r mount fs flags <<EOF
$(xray_cache_mount "$candidate")
EOF
	case "$fs" in ubifs|jffs2|ext4|ext3|ext2|f2fs|btrfs) ;; *) return 1 ;; esac
	case ",$flags," in *,rw,*) ;; *) return 1 ;; esac
	printf '%s' "$candidate"
}
xray_digest() {
	local digest
	digest="$(sha256sum "$1" 2>/dev/null)" || return 1
	digest="${digest%% *}"
	case "$digest" in ''|*[!0-9a-f]*) return 1 ;; esac
	[ "${#digest}" = 64 ] || return 1
	printf '%s' "$digest"
}
xray_cache_save() (
	# A subshell already isolates these variables (BusyBox ash rejects local here).
	bin="$1"
	[ -s "$bin" ] && [ -x "$bin" ] || return 1
	"$bin" version >/dev/null 2>&1 || return 1
	xray_requires_legacy_replacement "$bin" && return 1
	store="$(xray_cache_dir)" || { log 'Xray: постоянный кэш недоступен; после перезагрузки потребуется загрузка из сети'; return 1; }
	asset="$(xray_release_asset)" || return 1
	digest="$(xray_digest "$bin")" || return 1
	target="$store/$asset.$digest.gz"
	# An existing valid copy requires no Flash writes, including after reboot.
	if [ -s "$target" ] && gzip -t "$target" 2>/dev/null && [ "$(gzip -dc "$target" | sha256sum | cut -d' ' -f1)" = "$digest" ]; then return 0; fi
	umask 077
	mkdir -p "$store" || return 1
	chmod 700 "$store" || return 1
	# Writers hold bootstrap-lock; only incomplete staging files are disposable.
	rm -f "$store"/.new.*
	free="$(df -Pk "$store" | awk 'NR==2 { print $4 }')"
	case "$free" in ''|*[!0-9]*) return 1 ;; esac
	# Size is measured by streaming compression, without a second RAM copy.
	size="$(gzip -c "$bin" | wc -c)"
	case "$size" in ''|*[!0-9]*) return 1 ;; esac
	if [ "$size" -le 0 ] || [ "$size" -gt 16777216 ] || [ "$free" -lt "$(( (size+1023)/1024 + 2048 ))" ]; then
		log 'Xray: недостаточно места для постоянного кэша с резервом 2 МиБ; рабочий Xray сохранён'
		return 1
	fi
	temp="$(mktemp "$store/.new.XXXXXX")" || return 1
	trap 'rm -f "$temp"' EXIT
	trap 'exit 1' INT TERM
	gzip -c "$bin" >"$temp" && gzip -t "$temp" || return 1
	[ "$(gzip -dc "$temp" | sha256sum | cut -d' ' -f1)" = "$digest" ] || return 1
	[ "$(wc -c <"$temp")" -le 16777216 ] || return 1
	mv -f "$temp" "$target" || return 1
	# Once per binary update: commit the replacement before deleting the last
	# bootable copy. No Flash sync is performed by Heartbeat or normal startup.
	sync || return 1
	# Only after publishing the replacement may the previous copy be removed.
	for old in "$store"/*.gz; do [ "$old" = "$target" ] || rm -f "$old"; done
	log "Xray: сжатая загрузочная копия сохранена на постоянном разделе; bytes=$(wc -c <"$target")"
)
xray_cache_restore() (
	store="$(xray_cache_dir)" || return 1
	dir="$(xray_runtime_dir)"; mkdir -p "$dir" || return 1
	temp="$(mktemp "$dir/.restore.XXXXXX")" || return 1
	trap 'rm -f "$temp"' EXIT
	trap 'exit 1' INT TERM
	for cache in "$store"/*.gz; do
		[ -s "$cache" ] || continue
		[ "$(wc -c <"$cache")" -le 16777216 ] || continue
		digest="${cache%.gz}"; digest="${digest##*.}"
		case "$digest" in ''|*[!0-9a-f]*) continue ;; esac
		[ "${#digest}" = 64 ] || continue
		# Bound even an invalid compressed file; verify bytes before execution.
		gzip -t "$cache" 2>/dev/null || { log 'Xray: повреждён постоянный кэш; требуется повторная загрузка'; continue; }
		gzip -dc "$cache" | head -c 67108865 >"$temp"
		size="$(wc -c <"$temp")"
		[ "$size" -le 67108864 ] && [ "$(xray_digest "$temp")" = "$digest" ] || continue
		chmod 755 "$temp" && "$temp" version >/dev/null 2>&1 || continue
		xray_validate_transport_binary "$temp" || continue
		mv -f "$temp" "$dir/xray" || return 1
		if [ "$(uci_get xray_bin '')" != "$dir/xray" ]; then
			uci set "$CONFIG.$SECTION.xray_bin=$dir/xray" && uci commit "$CONFIG" || return 1
		fi
		log 'Xray: восстановлен из постоянного кэша без загрузки из интернета'
		return 0
	done
	return 1
)

# BEGIN SHARED ROUTER DOWNLOADER
# Shared, embedded in install.sh and the router agent by embed-router-download.py.
# No dependency on curl/jsonfilter/timeout is needed to bootstrap curl itself.
download_clock() {
	if [ -r /proc/uptime ]; then cut -d. -f1 /proc/uptime; else date +%s; fi
}
download_note() {
	if command -v log >/dev/null 2>&1; then log "$*"; else printf '%s\n' "$*" >&2; fi
}
download_origin() {
	local authority
	case "$1" in https://?*) ;; *) return 3 ;; esac
	authority="${1#https://}"; authority="${authority%%/*}"
	case "$authority" in ''|*[@\?\#\ ]*|*[!A-Za-z0-9.:-]*) return 3 ;; esac
	case "$authority" in *:*) ;; *) authority="$authority:443" ;; esac
	printf 'https://%s' "$authority"
}
download_signal_tree() {
	local child
	# Kill descendants first: a timed-out shell function may own a DNS client.
	if [ -r "/proc/$1/task/$1/children" ]; then
		for child in $(cat "/proc/$1/task/$1/children"); do download_signal_tree "$child" "$2"; done
	fi
	kill -"$2" "$1" 2>/dev/null || true
}
download_kill_tree() {
	local ticks
	download_signal_tree "$1" TERM
	# Allow shell EXIT traps to release locks and staging files first.
	ticks=0
	while kill -0 "$1" 2>/dev/null && [ "$ticks" -lt 2 ]; do sleep 1; ticks=$((ticks+1)); done
	download_signal_tree "$1" KILL
}
download_run() (
	seconds="$1"; shift; child=''
	trap 'result=$?; [ -z "$child" ] || { download_kill_tree "$child"; wait "$child" 2>/dev/null || true; }; exit "$result"' EXIT
	trap 'exit 28' INT TERM
	"$@" & child=$!
	ticks=0
	while kill -0 "$child" 2>/dev/null; do
		[ "$ticks" -lt "$seconds" ] || return 28
		sleep 1; ticks=$((ticks+1))
	done
	rc=0; wait "$child" || rc=$?; child=''; return "$rc"
)
download_curl() (
	url="$1"; dst="$2"; stats="$3"; method="$4"; deadline="$5"; hop=0
	while [ "$hop" -le 5 ]; do
		origin="$(download_origin "$url")" || return 3
		set -- -q -fsS --connect-timeout 10 --noproxy '*' --proto '=https' --max-filesize 33554432
		[ "$method" != HEAD ] || set -- "$@" -I
		DL_DEVICE=''; DL_RESOLVE=''
		# The agent resolves every redirect through its selected WAN. The
		# installer has no routing hook and uses the router's system resolver.
		if command -v download_route >/dev/null 2>&1; then download_route "$origin" || return $?; fi
		[ -z "$DL_DEVICE" ] || set -- "$@" --interface "$DL_DEVICE"
		[ -z "$DL_RESOLVE" ] || set -- "$@" --resolve "$DL_RESOLVE"
		remaining=$((deadline - $(download_clock)))
		[ "$remaining" -gt 0 ] || return 28
		rc=0
		curl "$@" --max-time "$remaining.000" -o "$dst" -w '%{http_code} %{redirect_url}\n' "$url" >"$stats" || rc=$?
		[ "$rc" = 0 ] || return "$rc"
		code=''; redirect=''; read -r code redirect <"$stats" || true
		case "$code" in
			301|302|303|307|308) [ -n "$redirect" ] || return 47; url="$redirect"; hop=$((hop+1)) ;;
			200) [ -s "$dst" ] || return 52; return 0 ;;
			*) return 22 ;;
		esac
	done
	return 47
)
download_reason() {
	case "$1" in
		3) printf invalid_https_url; return ;; 6) printf DNS; return ;;
		23|27) printf write; return ;; 28|124|137) printf timeout; return ;;
		35|51|58|60|77|80|82|83|90|91) printf TLS; return ;;
	esac
	if LC_ALL=C grep -Eqi 'no space|permission denied|read-only|write error|file too large' "$2"; then printf write
	elif LC_ALL=C grep -Eqi 'resolv|bad address|name or service|DNS' "$2"; then printf DNS
	elif LC_ALL=C grep -qi 'uclient context' "$2"; then printf client_context
	elif LC_ALL=C grep -Eqi 'TLS|SSL|certificate' "$2"; then printf TLS
	elif LC_ALL=C grep -Eqi 'timed out|timeout' "$2"; then printf timeout
	elif [ "$3" != 000 ]; then printf HTTP
	else printf network; fi
}
download_tools() {
	local tool path identity seen
	seen='|'
	for tool in curl uclient-fetch wget; do
		path="$(command -v "$tool" 2>/dev/null)" || continue
		identity="$(readlink -f "$path" 2>/dev/null)"; identity="${identity:-$path}"
		case "$seen" in *"|$identity|"*) continue ;; esac
		seen="$seen$identity|"; printf '%s\n' "$tool"
	done
}
remote_download() (
	url="$1"; dst="$2"; method="${3:-GET}"
	work="$(mktemp -d "${TMPDIR:-/tmp}/owrt-download.XXXXXX")" || return 23
	trap 'result=$?; rm -rf "$work"; [ "$result" = 0 ] || rm -f "$dst"; exit "$result"' EXIT
	trap 'exit 28' INT TERM
	unset http_proxy https_proxy HTTP_PROXY HTTPS_PROXY all_proxy ALL_PROXY
	# Also bound native clients and their error/response files on small RAM.
	ulimit -f 32768 || return 23
	deadline=$(( $(download_clock) + 120 ))
	[ -z "${DOWNLOAD_RESULT_FILE:-}" ] || : >"$DOWNLOAD_RESULT_FILE"
	for outer in "${XRAY_PREPARE_DEADLINE:-}" "${XRAY_FILE_DEADLINE:-}" "${DOWNLOAD_SOURCE_DEADLINE:-}"; do
		[ -z "$outer" ] || [ "$outer" -ge "$deadline" ] || deadline="$outer"
	done
	origin="$(download_origin "$url")" || { download_note 'Download: reason=invalid_https_url; rc=3'; return 3; }
	tools="$(download_tools)"; set -- $tools; left="$#"; rc=127
	[ "$left" -gt 0 ] || download_note 'Download: stage=tools; reason=no_http_client; rc=127'
	for tool in $tools; do
		remaining=$((deadline - $(download_clock)))
		[ "$remaining" -gt 0 ] || { rc=28; reason=timeout; break; }
		# Reserve time for genuinely different fallback clients. No blind
		# retries on dozens of releases when their common host is unavailable.
		seconds=$((remaining / left)); [ "$seconds" -gt 0 ] || seconds=1
		left=$((left-1)); attempt_end=$(( $(download_clock) + seconds ))
		rm -f "$dst"; : >"$work/stats"; : >"$work/error"; rc=0
		case "$tool" in
			curl) download_run "$seconds" download_curl "$url" "$dst" "$work/stats" "$method" "$attempt_end" 2>"$work/error" || rc=$? ;;
			*)
				if command -v download_native_notice >/dev/null 2>&1; then download_native_notice; fi
				download_run "$seconds" "$tool" -T "$seconds" -O "$dst" "$url" >"$work/stats" 2>"$work/error" || rc=$? ;;
		esac
		code=000
		if [ "$tool" = curl ]; then
			read -r code ignored <"$work/stats" || true
			case "$code" in [1-5][0-9][0-9]) ;; *) code=000 ;; esac
		else
			code="$(LC_ALL=C sed -n -e 's/.*HTTP\/[0-9.]*  *\([1-5][0-9][0-9]\).*/\1/p' -e 's/.*HTTP error \([1-5][0-9][0-9]\).*/\1/p' -e 's/.*awaiting response[. ]*\([1-5][0-9][0-9]\).*/\1/p' "$work/error" | tail -n 1)"
			code="${code:-000}"
		fi
		if [ "$rc" = 0 ]; then
			[ -s "$dst" ] && [ "$(wc -c <"$dst")" -le 33554432 ] || rc=23
		fi
		reason="$(download_reason "$rc" "$work/error" "$code")"
		[ "$rc" != 0 ] || reason=ok
		# Never print URLs, query strings, redirect signatures or raw headers.
		download_note "Download: stage=${DOWNLOAD_STAGE:-file}; tool=$tool; host=$origin; http=$code; rc=$rc; reason=$reason"
		[ -z "${DOWNLOAD_RESULT_FILE:-}" ] || printf '%s %s %s\n' "$rc" "$reason" "$code" >"$DOWNLOAD_RESULT_FILE"
		[ "$rc" != 0 ] || return 0
		case "$reason" in write|invalid_https_url) break ;; esac
	done
	[ "$rc" != 28 ] || download_note 'Download: reason=timeout; file/preparation deadline reached or HTTP client timed out'
	[ -z "${DOWNLOAD_RESULT_FILE:-}" ] || printf '%s %s %s\n' "$rc" "${reason:-no_http_client}" "${code:-000}" >"$DOWNLOAD_RESULT_FILE"
	return "$rc"
)
# END SHARED ROUTER DOWNLOADER

# Keep WAN policy for every curl redirect; native fallback uses system DNS.
download_route() {
    local host port ip
    truthy "$(uci_get wan_direct 0)" || return 0
    host="${1#https://}"; port="${host##*:}"; host="${host%:*}"
    DL_DEVICE="$(wan_device)" || return 1
    ip="$(wan_resolve_host "$host")" || return 6
    DL_RESOLVE="$host:$port:$ip"
}
fetch_file() { remote_download "$@"; }
download_native_notice() {
	if truthy "$(uci_get wan_direct 0)"; then log 'Download: native fallback uses system DNS; WAN settings unchanged'; fi
}
xray_native_fetch() (
    dst="$1"; shift
    trap 'result=$?; [ "$result" = 0 ] || rm -f "$dst"' EXIT
    ulimit -f 32768 || return 23
    download_run 120 "$@"
)
xray_prepare_timed() (
    now="$(download_clock)"; deadline=$((now + 300))
    [ -z "${XRAY_PREPARE_DEADLINE:-}" ] || [ "$XRAY_PREPARE_DEADLINE" -ge "$deadline" ] || deadline="$XRAY_PREPARE_DEADLINE"
    XRAY_PREPARE_DEADLINE="$deadline"
    export XRAY_PREPARE_DEADLINE
    remaining=$((deadline - now)); [ "$remaining" -gt 0 ] || return 28
    rc=0; download_run "$remaining" "$@" || rc=$?
    [ "$rc" != 28 ] || log 'Xray: preparation timeout (300s); existing Xray and cache preserved'
    return "$rc"
)

install_package() {
	local rc
	rc=0
	if command -v apk >/dev/null 2>&1; then
		log "Xray dependency: apk -U add $1"
		download_run 120 apk -U add "$1" >&2 || rc=$?
	elif command -v opkg >/dev/null 2>&1; then
		log "Xray dependency: opkg update && opkg install $1"
		download_run 120 opkg update >&2 && download_run 120 opkg install "$1" >&2 || rc=$?
	else
		log 'Xray: no supported package manager (apk/opkg)'
		return 1
	fi
	[ "$rc" = 0 ] || log "Xray dependency: $1 failed (rc=$rc)"
	return "$rc"
}

has_ca_certificates() {
	[ -s /etc/ssl/cert.pem ] && return 0
	[ -s /etc/ssl/certs/ca-certificates.crt ] && return 0
	[ -d /etc/ssl/certs ] && ls /etc/ssl/certs/* >/dev/null 2>&1 && return 0
	return 1
}

ensure_ca_certificates() {
	has_ca_certificates && return 0
	if command -v apk >/dev/null 2>&1; then
		install_package ca-certificates || true
	fi
	if ! command -v apk >/dev/null 2>&1 && command -v opkg >/dev/null 2>&1; then
		install_package ca-bundle || install_package ca-certificates || true
	fi
	has_ca_certificates
}

ensure_fetch_tool() {
	command -v curl >/dev/null 2>&1 && return 0
	command -v uclient-fetch >/dev/null 2>&1 && return 0
	command -v wget >/dev/null 2>&1 && return 0
	if command -v apk >/dev/null 2>&1; then
		install_package curl || install_package wget || true
	fi
	if ! command -v apk >/dev/null 2>&1 && command -v opkg >/dev/null 2>&1; then
		install_package curl || install_package wget-ssl || install_package wget || true
	fi
	command -v curl >/dev/null 2>&1 && return 0
	command -v uclient-fetch >/dev/null 2>&1 && return 0
	command -v wget >/dev/null 2>&1 && return 0
	return 1
}

install_xray_tmp() (
	xray_bootstrap_lock || return 1
	trap 'xray_bootstrap_unlock' EXIT
	trap 'exit 1' INT TERM
	install_xray_tmp_locked
)
xray_package_extract_binary() (
	archive="$1"
	output="$2"
	work="${output}.package-extract.$$"
	cleanup_package_extract() { rm -rf "$work"; }
	trap cleanup_package_extract EXIT
	trap 'exit 1' INT TERM
	mkdir -p "$work/data" || return 1
	# Select the extractor from the published release asset. Callers may also
	# supply a neutral temporary filename when reusing this helper.
	case "${3:-$archive}" in
		*.ipk|*.pkg)
			# yichya's .ipk release is a gzip-compressed tar containing
			# data.tar.gz. Support both this format and classic ar-wrapped ipk.
			if command -v ar >/dev/null 2>&1 && ar t "$archive" 2>/dev/null | grep -q 'data.tar'; then
				ar p "$archive" data.tar.gz >"$work/data.tar.gz" 2>/dev/null || rm -f "$work/data.tar.gz"
			else
				# BusyBox tar is more reliable with a real staging file than with
				# a multi-stage -O pipeline, especially on older OpenWrt builds.
				(cd "$work" && cat "$archive" | tar -xzf - ./data.tar.gz) >/dev/null 2>&1 || true
			fi
			if [ -s "$work/data.tar.gz" ] &&
				(cd "$work/data" && cat "$work/data.tar.gz" | tar -xzf - ./usr/bin/xray) >/dev/null 2>&1 &&
				[ -s "$work/data/usr/bin/xray" ]; then
				mv "$work/data/usr/bin/xray" "$output" || return 1
				return 0
			fi
			# Never fall back to `opkg install`: it could overwrite an active
			# /usr/bin/xray before our transport check has accepted the package.
			;;
		*.apk)
			# OpenWrt 25 uses APK v3/ADB, not a gzip tarball. Extract offline
			# into RAM; never install into /usr/bin or change the package DB.
			command -v apk >/dev/null 2>&1 || { log 'Xray: для извлечения APK требуется apk extract'; return 1; }
			if apk extract --allow-untrusted --no-chown --destination "$work/data" "$archive" >"$work/extract.log" 2>&1; then
				if [ -s "$work/data/usr/bin/xray" ] && [ ! -L "$work/data/usr/bin/xray" ]; then
					mv "$work/data/usr/bin/xray" "$output" || return 1
					return 0
				fi
				log 'Xray: APK извлечён, но в пакете нет обычного файла usr/bin/xray'
			else
				rc=$?
				log "Xray: ошибка apk extract (rc=$rc); системный Xray и база пакетов не изменены"
				head -c 4096 "$work/extract.log" >&2
			fi
			;;
	esac
	return 1
)

xray_binary_usable() {
	[ -x "$1" ] && "$1" version >/dev/null 2>&1 && ! xray_requires_legacy_replacement "$1"
}
xray_download_package() (
    url="$1"; package="$2"; tag="$3"; asset="$4"
    XRAY_FILE_DEADLINE=$(( $(download_clock) + 120 ))
    export XRAY_FILE_DEADLINE
    # No third-party proxy is assumed trusted. Opt-in mirrors serve only
    # published assets; the caller still verifies the OFFICIAL API digest.
    mirror="${XRAY_PACKAGE_MIRROR:-$(uci_get xray_package_mirror '')}"
    if [ -n "$mirror" ]; then
        case "$mirror" in *[\?\#\@]*|*[!A-Za-z0-9_./:+-]*) log 'Xray: invalid HTTPS mirror configuration'; return 3 ;; esac
        download_origin "$mirror" >/dev/null || return 3
        DOWNLOAD_SOURCE_DEADLINE=$(( $(download_clock) + 60 ))
    fi
    DOWNLOAD_STAGE=xray-package
    rc=0; fetch_file "$url" "$package" || rc=$?
    [ "$rc" != 0 ] || return 0
    unset DOWNLOAD_SOURCE_DEADLINE
    if [ -n "$mirror" ]; then
        log 'Xray: official asset download failed; trying configured HTTPS mirror with official SHA256'
        DOWNLOAD_STAGE=xray-mirror
        fetch_file "${mirror%/}/$tag/$asset" "$package" && return 0
        rc=$?
    else
        log 'Xray: HTTPS mirror not configured; no third-party download proxy used'
    fi
    return "$rc"
)

install_xray_tmp_locked() (
    XRAY_PREPARE_DEADLINE="${XRAY_PREPARE_DEADLINE:-$(( $(download_clock) + 300 ))}"
    export XRAY_PREPARE_DEADLINE
	dir="$(xray_runtime_dir)"
	mkdir -p "$dir" || return 1
	work="$(mktemp -d "$dir/.download.XXXXXX")" || return 1
	trap 'rm -rf "$work"' EXIT
	trap 'exit 1' INT TERM
	ensure_ca_certificates || { log 'Xray: stage=dependencies; trusted CA certificates unavailable; existing Xray preserved'; return 1; }
	ensure_fetch_tool || { log 'Xray: stage=dependencies; need curl, uclient-fetch or wget'; return 1; }
    command -v jsonfilter >/dev/null 2>&1 || install_package jsonfilter || { log 'Xray: stage=dependencies; jsonfilter unavailable'; return 1; }
	rc=1
	page=1
	while [ "$page" -le 10 ]; do
		[ "$(download_clock)" -lt "$XRAY_PREPARE_DEADLINE" ] || return 28
        xray_discover_releases "$work/candidates" "$work" "$page" || return $?
		while IFS='|' read -r tag asset url digest bytes; do
			# Keep the published name for native package-manager diagnostics.
			rm -f "$work/xray.new" "${package:-$work/unused}"
			package="$work/$asset"
            log "Xray: candidate: $asset; downloading verified GET (file <=120s, preparation <=300s)"
            DOWNLOAD_RESULT_FILE="$work/download-result"
            xray_download_package "$url" "$package" "$tag" "$asset" || {
                rc=$?; http=''; reason=''; ignored=''
                [ ! -s "$DOWNLOAD_RESULT_FILE" ] || read -r ignored reason http <"$DOWNLOAD_RESULT_FILE"
                log "ERROR: published Xray package found but download failed (rc=$rc; reason=${reason:-network}; http=${http:-unknown}); existing Xray preserved"
                # Only a confirmed missing asset may select another candidate.
                # DNS/TLS/timeout/403 must not trigger a storm of old downloads.
                case "$http" in 404|410) continue ;; *) return "$rc" ;; esac
            }
			[ "$(wc -c <"$package")" = "$bytes" ] || { log 'Xray: stage=verify; reason=size; package length mismatch'; rc=1; continue; }
			log 'Xray: verifying package checksum...'
			[ "$(xray_digest "$package")" = "$digest" ] || { log 'Xray: stage=verify; reason=SHA256; package SHA256 mismatch; existing Xray preserved'; rc=1; continue; }
			xray_check_package_metadata "$package" "$work" "$asset" || { rc=$?; continue; }
			xray_package_extract_binary "$package" "$work/xray.new" "$asset" || { rc=$?; log "Xray: extraction failed for $asset (rc=$rc)"; continue; }
			[ -s "$work/xray.new" ] && [ "$(wc -c <"$work/xray.new")" -le 67108864 ] || { rc=1; continue; }
			chmod 755 "$work/xray.new" || return 1
			"$work/xray.new" version >"$work/version" 2>&1 || { rc=$?; log "Xray: binary cannot run on this firmware (rc=$rc)"; head -c 4096 "$work/version" >&2; continue; }
			version="$(sed -n '1s/^Xray \([0-9][0-9.]*\) .*/\1/p' "$work/version")"
			[ "$version" = "${tag#v}" ] || { log 'Xray: binary version does not match release'; rc=1; continue; }
			xray_validate_transport_binary "$work/xray.new" || { rc=$?; continue; }
			log "Xray: compatible package found: $asset"
			# Publish and verify a bootable copy before replacing any executable.
			# Failure leaves both the old binary and UCI completely untouched.
			xray_cache_save "$work/xray.new" || { log 'Xray: persistent cache could not be created; existing Xray preserved'; return 1; }
			log 'Xray: persistent cache created; installing Xray...'
			mv -f "$work/xray.new" "$dir/xray" || return 1
			if [ "$(uci_get xray_bin '')" != "$dir/xray" ]; then
				uci set "$CONFIG.$SECTION.xray_bin=$dir/xray" && uci commit "$CONFIG" || return 1
			fi
			printf 'OK: Xray installed in %s\nOK: Xray %s\n' "$dir/xray" "$version"
			return 0
		done <"$work/candidates"
		[ -s "$work/next-release-page" ] || break
		read -r page <"$work/next-release-page" || return 1
		case "$page" in ''|*[!0-9]*) return 1 ;; esac
		log 'Xray: candidates rejected; searching older published releases...'
	done
	log 'ERROR: No compatible Xray package passed validation; existing Xray and cache preserved'
	return "$rc"
)

ensure_xray_available() {
	local configured candidate found
	configured="$(uci_get xray_bin /usr/bin/xray)"
	if [ -x "$configured" ]; then
		if xray_binary_usable "$configured"; then return 0; fi
		if xray_requires_legacy_replacement "$configured"; then
			log 'Xray: установленная версия запрещает текущий VLESS без TLS; поиск совместимой сборки из yichya/openwrt-xray'
		else
			log 'Xray: установленный бинарник не выполняет version; поиск проверенной рабочей сборки'
		fi
	fi

	for candidate in /usr/bin/xray /usr/bin/xray-core /usr/local/bin/xray /opt/bin/xray /tmp/owrt-xray/xray /tmp/owrt-xray/xray_softfloat /tmp/xray /tmp/xray_softfloat; do
		if xray_binary_usable "$candidate"; then
			found="$candidate"
			break
		fi
	done

	if [ -z "$found" ]; then
		found="$(command -v xray 2>/dev/null || command -v xray-core 2>/dev/null || true)"
	fi

	if [ -n "$found" ] && xray_binary_usable "$found"; then
		[ "$found" = "$configured" ] || {
			uci set "$CONFIG.$SECTION.xray_bin=$found"
			uci commit "$CONFIG"
			log "Xray found: $found"
		}
		return 0
	fi

	prepare_xray_tmp
}
prepare_xray_tmp() (
	xray_bootstrap_lock || return 1
	trap 'xray_bootstrap_unlock' EXIT
	trap 'exit 1' INT TERM
	# Recheck after acquiring the lock: a concurrent installer may have finished.
	configured="$(uci_get xray_bin /usr/bin/xray)"
	if xray_binary_usable "$configured"; then return 0; fi
	xray_cache_restore && return 0
	log 'Xray: загрузочной копии нет; требуется загрузка из сети'
	xray_prepare_timed install_xray_tmp_locked
)
prepare_xray() (
	ensure_xray_available || return $?
	bin="$(xray_bin_path)"
	case "$bin" in
		/tmp/*|"$(xray_runtime_dir)"/*)
			xray_bootstrap_lock || return 1
			trap 'xray_bootstrap_unlock' EXIT
			trap 'exit 1' INT TERM
			xray_cache_save "$bin" || { log 'Xray: запускается из RAM; автономное восстановление после перезагрузки пока недоступно'; return 1; }
			;;
	esac
)

ensure_xray_available_with_retry() {
	local attempts delay try_num managed
	attempts="${1:-18}"
	delay="${2:-10}"
	try_num=1
	managed="${OWRT_REMOTE_SERVICE_LOG:-0}"
	while [ "$try_num" -le "$attempts" ] || [ "$managed" = 1 ]; do
		if [ "$managed" = 1 ]; then
			truthy "$(uci_get enabled 0)" || return 1
			wait_for_selected_wan || return 1
		fi
		if ensure_xray_available; then
			return 0
		fi
		if [ "$try_num" -ge "$attempts" ]; then
			[ "$managed" = 1 ] || break
			delay=60
		fi
		log "Xray is not ready yet, retry in ${delay}s (${try_num}/${attempts})"
		sleep "$delay"
		try_num=$((try_num + 1))
	done
	return 1
}

wait_for_selected_wan() {
	local waiting
	waiting=0
	while truthy "$(uci_get wan_direct 0)"; do
		truthy "$(uci_get enabled 0)" || return 1
		if wan_select_interface >/dev/null; then
			[ "$waiting" = 0 ] || log 'Xray: выбранный WAN снова доступен; продолжается запуск туннеля'
			return 0
		fi
		[ "$waiting" = 1 ] || log 'Xray: ожидание выбранного WAN с физическим IPv4 default route; конфигурация сохранена'
		waiting=1
		sleep 5
	done
}

run_xray() {
	local enabled xray_bin xray_config
	xray_control_stopped && { log 'Xray: остановлен через Remote; Heartbeat продолжает работать'; return 0; }
	enabled="$(uci_get enabled 0)"
	truthy "$enabled" || die "service disabled: set option enabled '1'"

	# Missing WAN is a temporary condition, not a failed Xray configuration.
	# Stay supervised instead of exhausting procd's six startup attempts.
	wait_for_selected_wan || return 1
	ensure_xray_available_with_retry || die "cannot prepare Xray for tunnel"
	xray_bin="$(xray_bin_path)"
	xray_config="$(render_client_config)" || die "cannot create Xray configuration"
	[ -n "$xray_config" ] && [ -s "$xray_config" ] || die "Xray configuration is missing or empty"
	[ -x "$xray_bin" ] || die "xray not found or not executable: $xray_bin"
	log "Xray: запуск туннеля; config=$xray_config; VPS=$(uci_get vps_host ''):$(uci_get vps_port 8443); WAN_direct=$(uci_get wan_direct 0); WAN_selected=$(uci_get wan_interface wan)"

	if "$xray_bin" help 2>/dev/null | grep -q 'run'; then
		exec "$xray_bin" run -config "$xray_config"
	fi
	exec "$xray_bin" -config "$xray_config"
}

cmd="${1:-help}"
shift || true

case "$cmd" in
	help|-h|--help)
		usage
		;;
	status)
		status
		;;
	doctor)
		doctor
		;;
	wan-prepare)
		wan_prepare
		;;
	wan-preflight)
		wan_preflight
		;;
	wan-cleanup)
		wan_cleanup
		;;
	network-diagnostics)
		wan_diagnostics
		heartbeat_diagnostics
		;;
	install-xray-tmp)
		xray_prepare_timed install_xray_tmp
		;;
	prepare-xray)
		xray_prepare_timed prepare_xray
		;;
	xray-package-diagnostics)
		xray_package_diagnostics
		;;
	stop-xray)
		stop_xray
		;;
	xray-control-worker)
		xray_control_worker "$@"
		;;
	xray-control-execute)
		xray_control_execute "$@"
		;;
    tachyon-status)
        tachyon_json force
        ;;
    tachyon-reconfigure)
        tachyon_reconfigure
        ;;
	render-client)
		xray_apply_trace render-client
		render_client_config "$@" || exit $?
		xray_apply_trace render-client-ok
		;;
	run)
		run_xray
		;;
	heartbeat)
		xray_apply_trace heartbeat
		send_heartbeat "$@" || exit $?
		xray_apply_trace heartbeat-ok
		;;
	heartbeat-loop)
		heartbeat_loop
		;;
	heartbeat-diagnostics)
		heartbeat_diagnostics
		;;
	logs-sync)
		sync_global_logs
		;;
	*)
		usage >&2
		exit 2
		;;
esac
