#!/bin/sh













ezlink_elf_byte() {
	dd if="$1" bs=1 skip="$2" count=1 2>/dev/null
}

ezlink_arm_level() {
	distrib=$(sed -n "s/^DISTRIB_ARCH=['\"]*\([^'\"]*\).*/\1/p" "$1/etc/openwrt_release" 2>/dev/null)
	case "$distrib" in
	arm_cortex-a*) echo armv7; return ;;
	arm_*) echo unsupported; return ;;
	esac
	if [ -z "$1" ]; then
		case "$(uname -m 2>/dev/null)" in
		armv4*|armv5*|armv6*) echo unsupported; return ;;
		esac
	fi
	echo armv7
}

ezlink_router_arch() {
	root="${1:-}"
	elf=""
	for candidate in "$root/bin/busybox" "$root/bin/sh"; do
		if [ "$(ezlink_elf_byte "$candidate" 1)$(ezlink_elf_byte "$candidate" 2)$(ezlink_elf_byte "$candidate" 3)" = "ELF" ]; then
			elf="$candidate"
			break
		fi
	done
	if [ -z "$elf" ]; then
		[ -z "$root" ] || return 0
		case "$(uname -m 2>/dev/null)" in
		x86_64) echo x86_64 ;;
		aarch64) echo aarch64 ;;
		armv7*|armv8*) echo armv7 ;;
		mips*|"") ;;
		*) echo unsupported ;;
		esac
		return 0
	fi
	class=$(ezlink_elf_byte "$elf" 4)
	order=$(ezlink_elf_byte "$elf" 5)
	if [ "$order" = "$(printf '\001')" ]; then
		machine=$(ezlink_elf_byte "$elf" 18)
	elif [ "$order" = "$(printf '\002')" ]; then
		machine=$(ezlink_elf_byte "$elf" 19)
	else
		return 0
	fi
	if [ "$machine" = "$(printf '\076')" ] && [ "$class" = "$(printf '\002')" ]; then
		echo x86_64
	elif [ "$machine" = "$(printf '\267')" ] && [ "$class" = "$(printf '\002')" ]; then
		echo aarch64
	elif [ "$machine" = "$(printf '\050')" ] && [ "$class" = "$(printf '\001')" ] && [ "$order" = "$(printf '\001')" ]; then
		ezlink_arm_level "$root"
	elif [ "$machine" = "$(printf '\010')" ] && [ "$class" = "$(printf '\001')" ] && [ "$order" = "$(printf '\001')" ]; then
		echo mipsel
	else
		echo unsupported
	fi
}

# Dispatcher of the full package. The postinst normally replaces it with the
# matching core; it only runs when the router could not be identified then.
need=$(ezlink_router_arch)
core="/usr/lib/ezlink/quicksilver/cores/$need"
if [ -n "$need" ] && [ "$need" != unsupported ] && [ -x "$core" ]; then
	exec "$core" "$@"
fi
# LuCI reads the command's stdout as JSON.
printf '%s\n' '{"ok":false,"message":"这台路由器的处理器类型不受支持，无法运行代理核心"}'
exit 1
