#!/bin/sh
# Lucky v3 installer. POSIX sh; also tested with dash and BusyBox ash.
# The release URL contains v*/<core-version>_<product>/, v*/apk/ and/or v*/ipk/.

LC_ALL=C
export LC_ALL
umask 022
work=
previous_work=
stage=
launchd_stage=
base_url=
release=
product=
method=
ipk_available=0
apk_signed=0
apk_key_sha256=
apk_key_specified=0
# SHA256 of the public PEM, distributed with this installer via a trusted channel.
# A store can re-sign the standard APKs and pass its own trusted fingerprint.
apk_default_key_sha256=b7cb9f636d0e21287da2197b7069d7630139df3476e0b14632e270211b7a1aa0
install_dir=
core_arch=
core_os=Linux
assume_yes=0
no_start=0
dry_run=0
action=
update_package=
update_backend=
update_service_bin=
update_was_running=0
update_pending=0
update_replaced=0
update_keep_stage=0
update_launchd_disabled=0
update_launchd_temporary_enable=0

say() { printf '%s\n' "$*"; }
err() { printf '%s\n' "$*" >&2; }
die() { err "错误：$*"; exit 1; }
has() (
    # Small router shells may omit the command builtin. Keep the caller's PATH,
    # including Entware /opt paths, and never execute a tool just to find it.
    command -v "$1" >/dev/null 2>&1 && return 0
    type "$1" >/dev/null 2>&1 && return 0
    case "$1" in */*) [ -f "$1" ] && [ -x "$1" ]; return ;; esac
    search_path=${PATH-}
    while :; do
        search_dir=${search_path%%:*}
        [ -n "$search_dir" ] || search_dir=.
        [ -f "$search_dir/$1" ] && [ -x "$search_dir/$1" ] && return 0
        case "$search_path" in *:*) search_path=${search_path#*:} ;; *) return 1 ;; esac
    done
)
effective_uid() (
    # id may be absent, or present only as a BusyBox applet. USER/UID variables
    # are not proof of privilege; Padavan commonly calls its UID 0 user admin.
    value=$(id -u 2>/dev/null) || value=
    case "$value" in ''|*[!0-9]*) ;; *) printf '%s\n' "$value"; return 0 ;; esac
    value=$(busybox id -u 2>/dev/null) || value=
    case "$value" in ''|*[!0-9]*) ;; *) printf '%s\n' "$value"; return 0 ;; esac
    # Linux reports real, effective, saved and filesystem UIDs in this order.
    # Use shell builtins so this fallback needs neither id nor another applet.
    if [ -r "/proc/$$/status" ]; then
        while IFS=' 	' read -r label real effective rest; do
            [ "$label" = Uid: ] || continue
            case "$effective" in ''|*[!0-9]*) return 1 ;; esac
            printf '%s\n' "$effective"
            return 0
        done < "/proc/$$/status"
    fi
    return 1
)
is_root() {
    root_uid=$(effective_uid) || die '无法识别当前有效用户 ID；请检查 id、BusyBox 或 /proc，已停止操作。'
    [ "$root_uid" = 0 ]
}
cleanup() {
    if [ "$update_pending" = 1 ]; then
        trap '' 1 2 15
        rollback_core_update || { update_keep_stage=1; err "回退未完成，旧核心备份保留在：$stage/lucky.previous"; }
    fi
    if [ "$update_launchd_temporary_enable" = 1 ]; then
        launchctl disable system/com.lucky.daji || { update_keep_stage=1; err '无法恢复 launchd 原先禁用的自启状态。'; }
    fi
    [ -z "$launchd_stage" ] || { case "$launchd_stage" in /Library/LaunchDaemons/.com.lucky.daji.plist.*) rm -f "$launchd_stage" ;; esac; }
    [ -z "$stage" ] || [ "$update_keep_stage" = 1 ] || { case "$stage" in "$install_dir"/.install-v3-*) rm -rf "$stage" ;; esac; }
    [ -z "$work" ] || { case "$work" in */lucky-install-v3.*) rm -rf "$work" ;; esac; }
    [ -z "$previous_work" ] || { case "$previous_work" in */lucky-install-v3.*) rm -rf "$previous_work" ;; esac; }
    :
}
make_work() {
    wi=0
    while [ "$wi" -lt 20 ]; do
        work=${1:-${TMPDIR:-/tmp}}/lucky-install-v3.$$.$wi
        if (umask 077; mkdir "$work") 2>/dev/null; then
            trap cleanup 0
            trap 'exit 130' 1 2 15
            return
        fi
        wi=$((wi + 1))
    done
    work=
    die '无法创建临时目录。'
}
confirm() {
    [ "$assume_yes" = 1 ] && return 0
    printf '%s [y/N] ' "$*"
    IFS= read -r answer || return 1
    case "$answer" in y|Y|yes|YES|1) return 0 ;; *) return 1 ;; esac
}
choose() {
    # Write a result to selected, never interpolate user input into awk source.
    awk '{print NR ". " $0}' "$1"
    while :; do
        printf '%s (0 取消) > ' "$2"
        IFS= read -r answer || die '输入结束，已取消。'
        case "$answer" in 0) exit 0 ;; ''|*[!0-9]*) err '请输入有效编号。'; continue ;; esac
        selected=$(awk -v n="$answer" 'NR == n {print; exit}' "$1")
        [ -n "$selected" ] && return 0
        err '编号超出范围。'
    done
}
safe_name() {
    case "$1" in ''|.*|*[!a-zA-Z0-9._+-]*) return 1 ;; *) return 0 ;; esac
}
safe_dir() {
    case "$1" in
        /|/etc|/usr|/usr/share|/var|/root|/home|/opt|/data|/jffs|/etc/storage|/tmp|/proc|/proc/*|/sys|/sys/*|/dev|/dev/*|/run|/run/*|*..*|*/./*|*/.|*//*|*[!a-zA-Z0-9_./-]*) return 1 ;;
        /*) return 0 ;;
        *) return 1 ;;
    esac
}
fetch() (
    # Only baseline options: no wget --version/--show-progress, curl -k, or
    # GNU-only timeout flags. Never expose a failed partial download.
    fu=$1; fo=$2; progress=${3:-0}; attempt=0
    if [ "$progress" = 1 ]; then
        : > "$work/download.log" || exit 1
        # Keep stderr connected to the caller's terminal. Piping through tee
        # hides the TTY from BusyBox/fetch and can lose the downloader's status.
        exec 3>&2
    else
        exec 3>"$work/download.log"
    fi
    while [ "$attempt" -lt 2 ]; do
        if has curl; then
            set -- -f -L -S -o "$fo.part" "$fu"
            [ "$progress" = 1 ] || set -- -s "$@"
            if curl "$@" 2>&3; then
                mv "$fo.part" "$fo"; exit $?
            fi
        fi
        if has wget && wget -O "$fo.part" "$fu" 2>&3; then
            mv "$fo.part" "$fo"; exit $?
        fi
        if [ -x /usr/bin/fetch ]; then
            set -- -T 60 -o "$fo.part" "$fu"
            [ "$progress" = 1 ] || set -- -q "$@"
            if /usr/bin/fetch "$@" 2>&3; then
                mv "$fo.part" "$fo"; exit $?
            fi
        fi
        rm -f "$fo.part"
        attempt=$((attempt + 1))
        if [ "$progress" = 1 ] && [ "$attempt" -lt 2 ]; then
            err '下载未完成，重新尝试（2/2）。'
        fi
    done
    exit 1
)
fetch_sums() {
    fetch "$1" "$2.raw" || return 1
    # PowerShell-generated checksum lists can use CRLF; mawk does not treat
    # CR as field whitespace whereas some BusyBox awk versions do.
    tr -d '\015' < "$2.raw" > "$2"
}
links() {
    # Accept only single relative path components; ignore sort links, JS
    # templates, external URLs, parent links and percent-encoded path tricks.
    awk '
    { s=$0; while (match(s, /href[ \t]*=[ \t]*["\047][^"\047]*["\047]/)) {
        v=substr(s,RSTART,RLENGTH); s=substr(s,RSTART+RLENGTH)
        sub(/^[^=]*=[ \t]*["\047]/,"",v); sub(/["\047]$/,"",v)
        sub(/^\.\//,"",v); sub(/\/$/,"",v)
        if (v ~ /^[A-Za-z0-9][A-Za-z0-9._+-]*$/) print v
    }}' "$1" | sort -u
}
list_remote() {
    fetch "$1/" "$work/list.html" || die "无法读取目录：$1"
    links "$work/list.html" > "$2"
}
target_of() {
    case "$1" in
        *_wanji_docker) printf wanji_docker ;; *_wanji_admin) printf wanji_admin ;;
        *_lucky_docker) printf lucky_docker ;; *_xiaojv_waf) printf xiaojv_waf ;;
        *_wanji) printf wanji ;; *_xiaoman) printf xiaoman ;; *_lucky) printf lucky ;;
        *_xiaojv) printf xiaojv ;; *_gdy) printf gdy ;; *) return 1 ;;
    esac
}
select_release() {
    if [ -z "$release" ]; then
        list_remote "$base_url" "$work/root"
        awk '/^v[0-9][A-Za-z0-9._+-]*$/ {print}' "$work/root" | sort -r > "$work/versions"
        [ -s "$work/versions" ] || die '未找到版本目录。'
        choose "$work/versions" '请选择发布版本'
        release=$selected
    fi
    safe_name "$release" || die '版本目录名称无效。'
    release_url=$base_url/$release
    list_remote "$release_url" "$work/release"
    awk '/^[0-9][A-Za-z0-9._+-]*_(wanji|wanji_docker|wanji_admin|lucky|lucky_docker|xiaoman|xiaojv|xiaojv_waf|gdy)$/ {print}' "$work/release" > "$work/products"
    [ -s "$work/products" ] || die '版本目录中没有可安装的产品。'
    if [ -n "$product" ]; then
        selected=$(awk -v p="$product" '$0 == p {print}' "$work/products")
        if [ -z "$selected" ]; then
            while IFS= read -r candidate; do
                [ "$(target_of "$candidate")" != "$product" ] || printf '%s\n' "$candidate"
            done < "$work/products" > "$work/matches"
            [ "$(wc -l < "$work/matches" | tr -d ' ')" = 1 ] || die '产品不存在或存在多个核心版本，请指定完整产品目录名。'
            selected=$(cat "$work/matches")
        fi
    else
        choose "$work/products" '请选择产品'
    fi
    product_dir=$selected
    product=$(target_of "$product_dir") || die '未知产品。'
    core_version=${product_dir%_"$product"}
    [ "$action" != update ] || return 0
    apk_available=0
    if awk '$0=="apk" {found=1} END {exit !found}' "$work/release" &&
       fetch_sums "$release_url/apk/SHA256SUMS" "$work/shared.sums" &&
       fetch_sums "$release_url/apk/$product/SHA256SUMS" "$work/core.sums"; then
        if awk '$2 ~ /^[A-Za-z0-9_+-]+\/lucky-[A-Za-z0-9._+-]+[.]apk$/ {found=1} END {exit !found}' "$work/core.sums"; then
            apk_available=1
        fi
    fi
    ipk_available=0
    if awk '$0=="ipk" {found=1} END {exit !found}' "$work/release" &&
       fetch_sums "$release_url/ipk/SHA256SUMS" "$work/ipk-shared.sums" &&
       fetch_sums "$release_url/ipk/$product/SHA256SUMS" "$work/ipk-core.sums"; then
        if awk '$2 ~ /^[A-Za-z0-9_+-]+\/lucky_[A-Za-z0-9._+~-]+_[A-Za-z0-9_+-]+[.]ipk$/ {found=1} END {exit !found}' "$work/ipk-core.sums" &&
           one_package "$work/ipk-shared.sums" '^luci-app-lucky_[0-9][A-Za-z0-9._+~-]*_all[.]ipk$' >/dev/null &&
           one_package "$work/ipk-shared.sums" '^luci-i18n-lucky-zh-cn_[0-9][A-Za-z0-9._+~-]*_all[.]ipk$' >/dev/null; then
            ipk_available=1
        fi
    fi
}
is_openwrt() { [ -f /etc/openwrt_release ] && [ -f /etc/rc.common ]; }
ipk_architecture() {
    # opkg priorities describe compatible package architectures, not uname aliases.
    ia=$(opkg print-architecture 2>/dev/null) || return 1
    ia=$(printf '%s\n' "$ia" | awk '
        $1=="arch" && $2!="all" && $2!="noarch" && $3 ~ /^[0-9]+$/ {
            if (!found || $3+0>priority) {priority=$3+0; name=$2; found=1; ambiguous=0}
            else if ($3+0==priority && name!=$2) ambiguous=1
        }
        END {if (found && !ambiguous) print name; else exit 1}') || return 1
    safe_name "$ia" || return 1
    printf '%s\n' "$ia"
}
apk_architecture() {
    # --print-arch reports the binary's compile-time default (e.g. aarch64),
    # not OpenWrt's configured package architecture (e.g. aarch64_generic).
    aa=$(cat /etc/apk/arch 2>/dev/null) || aa=
    [ -n "$aa" ] || aa=$(sed -n "s/^DISTRIB_ARCH=['\"]\([^'\"]*\)['\"]$/\1/p" /etc/openwrt_release 2>/dev/null)
    [ -n "$aa" ] || aa=$(apk --print-arch 2>/dev/null)
    safe_name "$aa" || return 1
    printf '%s\n' "$aa"
}
read_elf_ident() (
    # Small BusyBox builds may omit od or custom hexdump formats. Validate
    # each reader before trying the next; nonempty output is not ELF evidence.
    for reader in od hexdump busybox; do
        case "$reader" in
            od) ei=$(od -A n -t u1 -N 6 "$1" 2>/dev/null) || ei= ;;
            hexdump) ei=$(hexdump -n 6 -v -b "$1" 2>/dev/null) || ei= ;;
            busybox) ei=$(busybox hexdump -n 6 -v -b "$1" 2>/dev/null) || ei= ;;
        esac
        ei=$(printf '%s\n' "$ei" | awk '
            NF==6 && $1==127 && $2==69 && $3==76 && $4==70 &&
            ($5==1 || $5==2) && ($6==1 || $6==2) {print $5+0, $6+0; found=1}
            NF==7 && $1=="0000000" && $2==177 && $3==105 && $4==114 && $5==106 &&
            ($6==1 || $6==2) && ($7==1 || $7==2) {print $6+0, $7+0; found=1}
            END {exit !found}') || continue
        printf '%s\n' "$ei"
        return 0
    done
    # The first six bytes of a valid ELF contain no NUL/newline. Comparing
    # them directly needs only dd and the shell's printf builtin.
    for reader in dd busybox; do
        case "$reader" in
            dd) ei=$(dd if="$1" bs=6 count=1 2>/dev/null) || continue ;;
            busybox) ei=$(busybox dd if="$1" bs=6 count=1 2>/dev/null) || continue ;;
        esac
        case "$ei" in
            "$(printf '\177ELF\001\001')") printf '1 1\n'; return 0 ;;
            "$(printf '\177ELF\001\002')") printf '1 2\n'; return 0 ;;
            "$(printf '\177ELF\002\001')") printf '2 1\n'; return 0 ;;
            "$(printf '\177ELF\002\002')") printf '2 2\n'; return 0 ;;
        esac
    done
    return 1
)
detect_core() {
    [ -z "$core_arch" ] || return 0
    machine=$(uname -m) || die '无法读取 CPU 架构。'
    # /bin/sh can be a wrapper. On Linux, inspect the running shell first.
    elf_ident=
    if [ "$core_os" = Linux ]; then elf_ident=$(read_elf_ident "/proc/$$/exe") || elf_ident=; fi
    [ -n "$elf_ident" ] || elf_ident=$(read_elf_ident /bin/sh) || elf_ident=
    elf_class=${elf_ident% *}
    endian=${elf_ident#* }
    bits=$(getconf LONG_BIT 2>/dev/null) || bits=
    case "$bits" in
        32|64) ;;
        *)
            case "$elf_class" in 1) bits=32 ;; 2) bits=64 ;; *) bits= ;; esac ;;
    esac
    case "$machine" in
        x86_64|amd64) if [ "$bits" = 32 ]; then core_arch=i386; else core_arch=x86_64; fi ;;
        i?86) core_arch=i386 ;;
        aarch64|arm64) if [ "$bits" = 32 ]; then core_arch=armv7; else core_arch=arm64; fi ;;
        armv8l|armv7*) core_arch=armv7 ;;
        armv6*) core_arch=armv6 ;;
        armv5*|arm) core_arch=armv5 ;;
        riscv64) core_arch=riscv64 ;;
        mips*)
            # EI_DATA of a userspace ELF, not a host-order guess from uname.
            case "$bits:$endian" in
                32:1) core_arch=mipsle_softfloat ;;
                64:1) core_arch=mips64le_softfloat ;;
                32:2) core_arch=mips_softfloat ;;
                64:2) core_arch=mips64_softfloat ;;
                *) die '无法识别 MIPS 用户空间位数或大小端，请使用 --arch 明确指定。' ;;
            esac
            ;;
        *) die "不支持或无法识别的 CPU 架构：$machine，请使用 --arch 指定。" ;;
    esac
    [ "$core_os" = Linux ] || return 0
    case "$core_arch" in
        armv6|armv7)
            if ! grep -i vfp /proc/cpuinfo >/dev/null 2>&1; then core_arch=armv5; fi ;;
    esac
    if [ "$core_arch" = i386 ] && ! grep -i sse2 /proc/cpuinfo >/dev/null 2>&1; then
        die '当前 i386 核心要求 SSE2；此 CPU 未检测到 SSE2。'
    fi
}
one_package() {
    awk -v pattern="$2" '$2 ~ pattern {print $2}' "$1" > "$work/package.matches"
    [ "$(wc -l < "$work/package.matches" | tr -d ' ')" = 1 ] || return 1
    cat "$work/package.matches"
}
prepare_apk() {
    [ "$apk_available" = 1 ] || { err '该产品没有发布 OpenWrt APK。'; return 1; }
    if ! is_openwrt || ! has apk; then err 'APK 安装需要使用 apk 包管理器的 OpenWrt 系统。'; return 1; fi
    apk_arch=$(apk_architecture) || { err '无法识别 OpenWrt APK 架构。'; return 1; }
    # Match the configured package architecture literally; never guess CPU aliases.
    awk -v prefix="$apk_arch/" 'index($2,prefix)==1 && $2 ~ /\/lucky-[A-Za-z0-9._+-]+[.]apk$/ {print $2}' "$work/core.sums" > "$work/core.matches"
    case "$(wc -l < "$work/core.matches" | tr -d ' ')" in
        0) err "该产品未发布适配此包架构的 APK：$apk_arch"; return 1 ;;
        1) ;;
        *) err "该产品存在多个匹配的 APK：$apk_arch，请检查发布清单。"; return 1 ;;
    esac
    core_apk=$(cat "$work/core.matches")
    luci_apk=$(one_package "$work/shared.sums" '^luci-app-lucky-[0-9][A-Za-z0-9._+-]*[.]apk$') || { err 'LuCI APK 缺失或重复。'; return 1; }
    lang_apk=$(one_package "$work/shared.sums" '^luci-i18n-lucky-zh-cn-[0-9][A-Za-z0-9._+-]*[.]apk$') || { err '中文语言 APK 缺失或重复。'; return 1; }
    return 0
}
prepare_ipk() {
    [ "$ipk_available" = 1 ] || { err '该产品没有发布完整的 OpenWrt IPK。'; return 1; }
    if ! is_openwrt || ! has opkg; then err 'IPK 安装需要使用 opkg 包管理器的 OpenWrt 系统。'; return 1; fi
    ipk_arch=$(ipk_architecture) || { err '无法唯一识别 OpenWrt IPK 架构。'; return 1; }
    awk -v prefix="$ipk_arch/lucky_" -v suffix="_$ipk_arch.ipk" '
        index($2,prefix)==1 && $2 ~ /^[A-Za-z0-9_+-]+\/lucky_[A-Za-z0-9._+~-]+[.]ipk$/ &&
        substr($2,length($2)-length(suffix)+1)==suffix {print $2}' "$work/ipk-core.sums" > "$work/ipk-core.matches"
    case "$(wc -l < "$work/ipk-core.matches" | tr -d ' ')" in
        0) err "该产品未发布适配此包架构的 IPK：$ipk_arch"; return 1 ;;
        1) ;;
        *) err "该产品存在多个匹配的 IPK：$ipk_arch，请检查发布清单。"; return 1 ;;
    esac
    core_ipk=$(cat "$work/ipk-core.matches")
    luci_ipk=$(one_package "$work/ipk-shared.sums" '^luci-app-lucky_[0-9][A-Za-z0-9._+~-]*_all[.]ipk$') || { err 'LuCI IPK 缺失或重复。'; return 1; }
    lang_ipk=$(one_package "$work/ipk-shared.sums" '^luci-i18n-lucky-zh-cn_[0-9][A-Za-z0-9._+~-]*_all[.]ipk$') || { err '中文语言 IPK 缺失或重复。'; return 1; }
    return 0
}
select_method() {
    if [ -n "$method" ]; then
        [ "$method" != apk ] || prepare_apk || die '不能使用所选 APK 安装方式；可以改选 tar。'
        [ "$method" != ipk ] || prepare_ipk || die '不能使用所选 IPK 安装方式；可以改选 tar。'
        return
    fi
    printf '%s\n' '仅安装 Linux 核心（tar.gz）' > "$work/methods"
    # A product may publish packages for other CPUs or package managers only.
    # Resolve the complete triple for this device before offering its menu entry.
    if [ "$apk_available" = 1 ] && is_openwrt && has apk && prepare_apk; then
        printf '%s\n' '安装 OpenWrt APK（核心 + LuCI + 中文语言包）' >> "$work/methods"
    fi
    if [ "$ipk_available" = 1 ] && is_openwrt && has opkg && prepare_ipk; then
        printf '%s\n' '安装 OpenWrt IPK（核心 + LuCI + 中文语言包）' >> "$work/methods"
    fi
    if [ "$(wc -l < "$work/methods" | tr -d ' ')" = 1 ] && is_openwrt; then
        say '当前产品没有适配本机的 APK/IPK，可选择 tar.gz 仅安装核心。'
    fi
    while :; do
        choose "$work/methods" '请选择安装方式'
        case "$selected" in
            '仅安装 Linux'*) method=tar; return ;;
            '安装 OpenWrt APK'*) if prepare_apk; then method=apk; return; fi ;;
            '安装 OpenWrt IPK'*) if prepare_ipk; then method=ipk; return; fi ;;
        esac
    done
}
hash_file() (
    # Check the tool's exit status before parsing its output. A pipeline to
    # awk can hide a failed applet and report an empty digest as success.
    for hash_tool in sha256sum sha256 shasum busybox openssl; do
        case "$hash_tool" in
            sha256sum) hash_output=$(sha256sum < "$1" 2>/dev/null) || continue ;;
            sha256) hash_output=$(sha256 -q < "$1" 2>/dev/null) || continue ;;
            shasum) hash_output=$(shasum -a 256 < "$1" 2>/dev/null) || continue ;;
            busybox) hash_output=$(busybox sha256sum < "$1" 2>/dev/null) || continue ;;
            openssl) hash_output=$(openssl dgst -sha256 < "$1" 2>/dev/null) || continue ;;
        esac
        digest=$(printf '%s\n' "$hash_output" | awk -v tool="$hash_tool" '
            NF {n++; hash=(tool=="openssl" ? $NF : $1)}
            END {
                if (n==1 && length(hash)==64 && hash !~ /[^0-9a-fA-F]/) print tolower(hash)
                else exit 1
            }') || continue
        printf '%s\n' "$digest"
        return 0
    done
    return 1
)
download_file() {
    say "下载：$2"
    fetch "$1/$2" "$3" 1 || { cat "$work/download.log" >&2; die "下载失败：$2"; }
}
find_existing() {
    existing=
    record=/etc/lucky-install-v3
    [ "$core_os" != darwin ] || record=/usr/local/etc/lucky-install-v3
    is_root || record=$HOME/.config/lucky-install-v3
    if [ -f "$record" ]; then
        existing=$(sed -n 's/^directory=//p' "$record")
        safe_dir "$existing" && [ -f "$existing/lucky" ] && return
        existing=
    fi
    for profile in /etc/profile /opt/etc/profile /jffs/configs/profile.add "$HOME/.bashrc"; do
        [ -f "$profile" ] || continue
        candidate=$(sed -n 's/^[ ]*export luckydir="\([^"]*\)"[ ]*$/\1/p' "$profile" | tail -n 1)
        if safe_dir "$candidate" && [ -f "$candidate/lucky" ]; then existing=$candidate; return; fi
    done
    for candidate in /etc/lucky.daji /usr/local/etc/lucky.daji /usr/share/lucky.daji /data/lucky.daji /data/userdisk/lucky.daji /jffs/lucky.daji /etc/storage/lucky.daji "$HOME/.local/share/lucky.daji"; do
        if [ -f "$candidate/lucky" ]; then existing=$candidate; return; fi
    done
}
choose_dir() {
    if [ -z "$install_dir" ]; then
        install_dir=$existing
        if [ -z "$install_dir" ]; then
            install_dir=/etc/lucky.daji
            case "$core_os" in freebsd|darwin) install_dir=/usr/local/etc/lucky.daji ;; esac
            is_root || install_dir=$HOME/.local/share/lucky.daji
            [ ! -d /jffs ] || install_dir=/jffs/lucky.daji
            [ ! -f /etc/storage/started_script.sh ] || install_dir=/etc/storage/lucky.daji
            [ ! -f /data/etc/crontabs/root ] || install_dir=/data/lucky.daji
        fi
        if [ "$assume_yes" != 1 ]; then
            printf '安装目录 [%s]（可输入其他绝对路径） > ' "$install_dir"
            IFS= read -r candidate || die '输入结束，已取消。'
            [ -z "$candidate" ] || install_dir=$candidate
        fi
    fi
    install_dir=${install_dir%/}
    safe_dir "$install_dir" || die '安装目录必须为安全的绝对路径，仅支持字母、数字、点、下划线和连字符。'
    [ -z "$existing" ] || [ "$existing" = "$install_dir" ] || die "已存在安装：$existing。请在原目录升级或先卸载。"
}
available_kib() {
    df -k "$1" 2>/dev/null | awk 'NR>1 && NF>=4 {v=$(NF-2)} END {if(v ~ /^[0-9]+$/) print v}'
}
check_space() {
    # Work in KiB and use awk numbers: do not overflow 32-bit shell arithmetic.
    space=$(available_kib "$1")
    if [ -n "$space" ]; then
        awk -v free="$space" -v need="$2" 'BEGIN {exit !(free >= need)}' || die "目录 $1 空间不足，需要约 $2 KiB，可用 $space KiB。"
    else err "提示：无法读取 $1 的可用空间，将依靠实际写入检查。"
    fi
}
work_filesystem() {
    df -k "$1" 2>/dev/null | awk 'NR>1 && NF>=4 {mount=$NF} END {print mount}'
}
move_core_work() {
    current_real=$(CDPATH='' cd "$work" && pwd -P) || die '无法访问当前临时目录。'
    target_real=$(CDPATH='' cd "$1" && pwd -P) || die '无法访问临时文件目标目录。'
    # Never copy a work directory into its own descendant, including aliases.
    case "$target_real/" in "$current_real/"*) return 0 ;; esac
    previous_work=$work
    make_work "$1"
    cp -R "$previous_work/." "$work/" || die '无法转移安装临时文件，原程序未替换。'
    case "$previous_work" in
        */lucky-install-v3.*) rm -rf "$previous_work" || die '无法清理原临时目录。' ;;
        *) die '原临时目录路径异常，未清理。' ;;
    esac
    previous_work=
}
select_core_work() {
    # Keep small menu files in the initial work directory, then put large
    # archives on whichever selected filesystem has more available space.
    current_free=$(available_kib "$work")
    target_free=$(available_kib "$install_dir")
    core_work_parent=$(dirname "$work")
    if [ -n "$target_free" ] &&
        awk -v current="$current_free" -v target="$target_free" 'BEGIN {exit !(target > 0 && (current == "" || target > current))}'; then
        move_core_work "$install_dir"
    fi
    say "下载与解压临时目录：$work"
}
check_core_space() {
    # Use measured archive, expanded tar and old core sizes, without a fixed
    # reserve. The downloaded gzip already occupies space, so df excludes it.
    old_kib=0
    if [ -f "$install_dir/lucky" ]; then
        old_kib=$(wc -c < "$install_dir/lucky" | awk '{printf "%.0f", ($1+1023)/1024}')
    fi
    install_need=$(awk -v tar="$tar_kib" -v old="$old_kib" -v action="$action" 'BEGIN {
        if (action=="update" && tar>old) old=tar
        printf "%.0f", tar+old
    }')
    cache_need=$tar_kib
    gzip_kib=$(wc -c < "$work/core.tar.gz" | awk '{printf "%.0f", ($1+1023)/1024}')
    # On one filesystem: gzip+tar, then tar+new core, then new core+backup.
    # Gzip and tar are removed between phases; reserve the peak, not their sum.
    shared_need=$(awk -v tar="$tar_kib" -v old="$old_kib" -v gz="$gzip_kib" 'BEGIN {
        extra=(tar>old ? tar : old)
        peak=tar+extra-gz
        if (peak<tar) peak=tar
        printf "%.0f", peak
    }')
    cache_fs=$(work_filesystem "$work")
    install_fs=$(work_filesystem "$install_dir")
    if [ -z "$cache_fs" ] || [ -z "$install_fs" ] || [ "$cache_fs" = "$install_fs" ]; then
        current_free=$(available_kib "$work")
        # A larger install partition may fit the core but not both core and
        # cache together. Use the original temporary partition when they fit
        # separately, accounting for the gzip transfer before moving anything.
        origin_fs=$(work_filesystem "$core_work_parent")
        origin_free=$(available_kib "$core_work_parent")
        if [ -n "$current_free" ] && [ -n "$origin_free" ] && [ -n "$origin_fs" ] &&
            [ -n "$install_fs" ] && [ "$origin_fs" != "$install_fs" ] &&
            awk -v current="$current_free" -v origin="$origin_free" -v gz="$gzip_kib" \
                -v shared="$shared_need" -v cache="$cache_need" -v install="$install_need" \
                'BEGIN {exit !(current<shared && origin>=gz+cache && current+gz>=install)}'; then
            move_core_work "$core_work_parent"
            say "为安装和备份预留空间，临时目录调整为：$work"
            cache_fs=$(work_filesystem "$work")
        fi
    fi
    if [ -z "$cache_fs" ] || [ -z "$install_fs" ] || [ "$cache_fs" = "$install_fs" ]; then
        check_space "$work" "$shared_need"
    else
        check_space "$work" "$cache_need"
        check_space "$install_dir" "$install_need"
    fi
}
stop_tar() {
    if is_root; then
        if [ "$core_os" = darwin ] && launchctl print system/com.lucky.daji >/dev/null 2>&1; then
            launchctl bootout system/com.lucky.daji || return 1
        fi
        if [ "$core_os" = freebsd ] && [ -x /usr/local/etc/rc.d/lucky_daji ]; then
            if /usr/local/etc/rc.d/lucky_daji onestatus >/dev/null 2>&1; then
                /usr/local/etc/rc.d/lucky_daji onestop || return 1
            fi
        fi
        if [ -d /run/systemd/system ] && has systemctl; then systemctl stop lucky.daji.service 2>/dev/null || :; fi
        if [ -x /etc/init.d/lucky.daji ]; then /etc/init.d/lucky.daji stop 2>/dev/null || :; fi
    fi
    [ ! -x "$install_dir/lucky-service" ] || "$install_dir/lucky-service" stop || return 1
    # Legacy installs do not have our PID file. Only stop the selected executable.
    for pid in $(core_pids "$install_dir"); do
        kill "$pid" 2>/dev/null || :
    done
    wait_count=0
    while running_tar; do
        [ "$wait_count" -lt 10 ] || { err '旧进程未退出，已停止升级。'; return 1; }
        sleep 1; wait_count=$((wait_count + 1))
    done
}
tmp_allows_execution() (
    # Execute the probe directly so a noexec mount cannot pass via /bin/sh.
    probe_index=0
    while [ "$probe_index" -lt 20 ]; do
        probe_dir=$1/lucky-exec-check.$$.$probe_index
        if (umask 077; mkdir "$probe_dir") 2>/dev/null; then
            trap 'rm -f "$probe_dir/check"; rmdir "$probe_dir"' 0
            printf '#!/bin/sh\nexit 0\n' > "$probe_dir/check" &&
                chmod 700 "$probe_dir/check" && "$probe_dir/check" 2>/dev/null
            exit $?
        fi
        probe_index=$((probe_index + 1))
    done
    return 1
)
select_service_tmpdir() {
    service_tmpdir=$install_dir/.lucky-tmp
    # The legacy MIPS loader may need much more space than router /tmp has.
    # Keep its executable backing files on the installation filesystem; this
    # is independent of the application's upload/cache TMPDIR policy below.
    service_upx_tmpdir=$install_dir/.lucky-tmp
    # Routers and non-systemd Linux usually have a RAM-backed /tmp and a small
    # persistent install partition. Keep large legacy uploads off that partition.
    # Retain the existing systemd/other-OS fallback for service security policies.
    if [ "$core_os" = Linux ] && { is_openwrt || [ ! -d /run/systemd/system ]; }; then
        if tmp_allows_execution /tmp; then service_tmpdir=/tmp; fi
    fi
}
prepare_service_tmpdir() {
    [ ! -L "$install_dir/.lucky-tmp" ] || return 1
    (umask 077; mkdir -p "$install_dir/.lucky-tmp") && chmod 700 "$install_dir/.lucky-tmp"
}
write_runner() {
    select_service_tmpdir
    cat > "$install_dir/lucky-service" <<EOF
#!/bin/sh
DIR='$install_dir'
TMPDIR='$service_tmpdir'
UPX_TMPDIR='$service_upx_tmpdir'
export TMPDIR UPX_TMPDIR
EOF
    cat >> "$install_dir/lucky-service" <<'EOF'
running() {
    # Web upgrades change the PID. Match the executable, never trust a stale PID file.
    if [ "$(uname -s)" = Darwin ]; then
        pid=$(/usr/sbin/lsof -t -a -d txt "$DIR/lucky" 2>/dev/null | head -n 1)
        [ -n "$pid" ] && return 0
    elif [ "$(uname -s)" = FreeBSD ]; then
        pid=$(procstat -b -a 2>/dev/null | awk -v exe="$DIR/lucky" '$NF==exe {print $1; exit}')
        [ -n "$pid" ] && return 0
    else
        # /opt commonly points at a USB volume on routers. procfs reports the
        # physical directory, including for an old inode after a web upgrade.
        physical_dir=$(CDPATH='' cd "$DIR" 2>/dev/null && pwd -P) || physical_dir=$DIR
        link_reader=
        if command -v readlink >/dev/null 2>&1 || type readlink >/dev/null 2>&1; then
            link_reader=readlink
        elif busybox readlink /proc/$$/exe >/dev/null 2>&1; then
            link_reader=busybox
        fi
        for proc in /proc/[0-9]*/exe; do
            exe=
            case "$link_reader" in
                readlink) exe=$(readlink "$proc" 2>/dev/null) || exe= ;;
                busybox) exe=$(busybox readlink "$proc" 2>/dev/null) || exe= ;;
            esac
            case "$exe" in
                "$DIR/lucky"|"$DIR/lucky (deleted)"|"$physical_dir/lucky"|"$physical_dir/lucky (deleted)")
                    pid=${proc#/proc/}; pid=${pid%/exe}; return 0 ;;
                ''|"$DIR"/.install-v3-*/*|"$physical_dir"/.install-v3-*/*)
                    # Some Padavan builds omit readlink, and Linux 3.4 can lose
                    # exe for a running UPX core. Require both its process name
                    # and exact installed argv[0] before accepting that fallback.
                    if [ -z "$exe" ]; then
                        IFS= read -r process_name 2>/dev/null < "${proc%/exe}/comm" || continue
                        [ "$process_name" = lucky ] || continue
                    fi
                    # Older kernels can retain the staging path after rollback.
                    # Only match a service launched from DIR/lucky, not -info
                    # probes or other tools executed inside a staging directory.
                    arg0=$(tr '\000' '\n' < "${proc%/exe}/cmdline" 2>/dev/null | head -n 1)
                    case "$arg0" in "$DIR/lucky"|"$physical_dir/lucky")
                        pid=${proc#/proc/}; pid=${pid%/exe}; return 0 ;;
                    esac ;;
            esac
        done
    fi
    return 1
}
case "${1:-start}" in
    start)
        running && exit 0
        if [ "$(uname -s)" = Darwin ] && [ "$(id -u)" = 0 ] &&
           [ "$(/usr/libexec/PlistBuddy -c 'Print :ProgramArguments:0' /Library/LaunchDaemons/com.lucky.daji.plist 2>/dev/null)" = "$DIR/lucky" ]; then
            if launchctl print system/com.lucky.daji >/dev/null 2>&1; then
                launchctl kickstart system/com.lucky.daji || exit 1
            else
                launchctl bootstrap system /Library/LaunchDaemons/com.lucky.daji.plist || exit 1
            fi
            sleep 2
            running
            exit $?
        fi
        if command -v nohup >/dev/null 2>&1 || type nohup >/dev/null 2>&1; then
            nohup "$DIR/lucky" -c "$DIR/lucky.conf" -cd "$DIR" >> "$DIR/lucky.log" 2>&1 &
        else "$DIR/lucky" -c "$DIR/lucky.conf" -cd "$DIR" >> "$DIR/lucky.log" 2>&1 &
        fi
        echo $! > "$DIR/lucky.pid"
        sleep 2
        running ;;
    stop)
        if [ "$(uname -s)" = Darwin ] && [ "$(id -u)" = 0 ] &&
           [ "$(/usr/libexec/PlistBuddy -c 'Print :ProgramArguments:0' /Library/LaunchDaemons/com.lucky.daji.plist 2>/dev/null)" = "$DIR/lucky" ] &&
           launchctl print system/com.lucky.daji >/dev/null 2>&1; then
            launchctl bootout system/com.lucky.daji || exit 1
        fi
        if running; then
            kill "$pid" || exit 1
            i=0
            while running; do
                [ "$i" -lt 10 ] || exit 1
                sleep 1; i=$((i+1))
            done
        fi
        rm -f "$DIR/lucky.pid" ;;
    status) running ;;
    *) exit 1 ;;
esac
EOF
    chmod 755 "$install_dir/lucky-service" || die '无法写入启动脚本。'
}
cron_update() {
    has crontab || return 1
    crontab -l > "$work/cron.old" 2>/dev/null || :
    awk 'index($0,"# Lucky-install-v3")==0 && index($0,"#lucky保守模式守护进程")==0' "$work/cron.old" > "$work/cron.new"
    [ "$1" != add ] || printf '* * * * * %s/lucky-service start >/dev/null 2>&1 # Lucky-install-v3\n' "$install_dir" >> "$work/cron.new"
    crontab "$work/cron.new"
}
router_hook() {
    hook=
    if [ -f /etc/storage/started_script.sh ]; then hook=/etc/storage/started_script.sh
    elif [ -d /jffs/scripts ]; then hook=/jffs/scripts/init-start
    elif [ -f /jffs/.asusrouter ]; then hook=/jffs/.asusrouter
    fi
    [ -n "$hook" ] || return 0
    if [ -f "$hook" ]; then
        awk 'index($0,"# Lucky-install-v3")==0 && index($0,"#Lucky启动脚本")==0' "$hook" > "$work/hook"
    else printf '#!/bin/sh\n' > "$work/hook"
    fi
    [ "$1" != add ] || printf '%s/lucky-service start # Lucky-install-v3\n' "$install_dir" >> "$work/hook"
    cat "$work/hook" > "$hook" && chmod 755 "$hook"
}
setup_service() {
    service_kind=manual
    # Keep a private fallback for old cores when /tmp cannot execute uploads.
    prepare_service_tmpdir || return 1
    if is_root && [ "$core_os" = darwin ]; then
        service_kind=launchd
        mkdir -p /Library/LaunchDaemons || return 1
        cat > "$work/com.lucky.daji.plist" <<EOF
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0"><dict>
    <key>Label</key><string>com.lucky.daji</string>
    <key>ProgramArguments</key><array>
        <string>$install_dir/lucky</string>
        <string>-c</string><string>$install_dir/lucky.conf</string>
        <string>-cd</string><string>$install_dir</string>
    </array>
    <key>WorkingDirectory</key><string>$install_dir</string>
    <key>EnvironmentVariables</key><dict>
        <key>TMPDIR</key><string>$service_tmpdir</string>
    </dict>
    <key>RunAtLoad</key><true/>
    <key>KeepAlive</key><dict><key>SuccessfulExit</key><false/></dict>
    <key>ThrottleInterval</key><integer>3</integer>
    <key>StandardOutPath</key><string>$install_dir/lucky.log</string>
    <key>StandardErrorPath</key><string>$install_dir/lucky.log</string>
</dict></plist>
EOF
        plutil -lint "$work/com.lucky.daji.plist" || return 1
        launchd_stage=/Library/LaunchDaemons/.com.lucky.daji.plist.$$
        [ ! -e "$launchd_stage" ] && [ ! -L "$launchd_stage" ] || return 1
        cp "$work/com.lucky.daji.plist" "$launchd_stage" &&
            chown root:wheel "$launchd_stage" && chmod 644 "$launchd_stage" &&
            mv "$launchd_stage" /Library/LaunchDaemons/com.lucky.daji.plist || return 1
        launchd_stage=
        launchctl enable system/com.lucky.daji || return 1
    elif is_root && [ "$core_os" = freebsd ]; then
        mkdir -p /usr/local/etc/rc.d || return 1
        cat > /usr/local/etc/rc.d/lucky_daji <<EOF
#!/bin/sh
# PROVIDE: lucky_daji
# REQUIRE: LOGIN NETWORKING
# KEYWORD: shutdown
. /etc/rc.subr
name=lucky_daji
rcvar=lucky_daji_enable
load_rc_config \$name
: \${lucky_daji_enable:=NO}
command=/usr/sbin/daemon
TMPDIR='$service_tmpdir'
export TMPDIR
pidfile=/var/run/lucky_daji.pid
command_args="-f -r -P \$pidfile -p '$install_dir/lucky.pid' -o '$install_dir/lucky.log' '$install_dir/lucky' -c '$install_dir/lucky.conf' -cd '$install_dir'"
run_rc_command "\$1"
EOF
        chmod 755 /usr/local/etc/rc.d/lucky_daji && sysrc lucky_daji_enable=YES || return 1
        service_kind=freebsd
    elif is_root && is_openwrt; then
        if [ -f /lib/functions/procd.sh ]; then
            cat > /etc/init.d/lucky.daji <<EOF
#!/bin/sh /etc/rc.common
START=99
STOP=15
USE_PROCD=1
start_service() {
    procd_open_instance
    procd_set_param command '$install_dir/lucky' -c '$install_dir/lucky.conf' -cd '$install_dir'
    procd_set_param env TMPDIR='$service_tmpdir' UPX_TMPDIR='$service_upx_tmpdir'
    procd_set_param respawn 3600 5 5
    procd_set_param stdout 1
    procd_set_param stderr 1
    procd_close_instance
}
EOF
        else
            cat > /etc/init.d/lucky.daji <<EOF
#!/bin/sh /etc/rc.common
START=99
start() { '$install_dir/lucky-service' start; }
stop() { '$install_dir/lucky-service' stop; }
EOF
        fi
        chmod 755 /etc/init.d/lucky.daji && /etc/init.d/lucky.daji enable || return 1
        service_kind=openwrt
    elif is_root && [ -d /run/systemd/system ] && has systemctl; then
        cat > /etc/systemd/system/lucky.daji.service <<EOF
[Unit]
Description=Lucky
After=network.target
[Service]
Type=simple
Environment=TMPDIR=$service_tmpdir
Environment=UPX_TMPDIR=$service_upx_tmpdir
ExecStart=$install_dir/lucky -c $install_dir/lucky.conf -cd $install_dir
Restart=on-failure
RestartSec=3
[Install]
WantedBy=multi-user.target
EOF
        chmod 644 /etc/systemd/system/lucky.daji.service
        systemctl daemon-reload && systemctl enable lucky.daji.service || return 1
        service_kind=systemd
    elif is_root && has rc-update && [ -f /sbin/openrc-run ]; then
        cat > /etc/init.d/lucky.daji <<EOF
#!/sbin/openrc-run
command='$install_dir/lucky'
export TMPDIR='$service_tmpdir'
export UPX_TMPDIR='$service_upx_tmpdir'
command_args='-c $install_dir/lucky.conf -cd $install_dir'
command_background=true
pidfile='$install_dir/lucky.pid'
depend() { need localmount; use net; }
# The updater restarts Lucky with a new PID; the runner checks the executable.
stop() {
    ebegin "Stopping Lucky"
    '$install_dir/lucky-service' stop
    eend \$?
}
EOF
        chmod 755 /etc/init.d/lucky.daji && rc-update add lucky.daji default || return 1
        service_kind=openrc
    elif cron_update add; then service_kind=cron
    else err '没有可用的服务管理器或 crontab；可用 lucky-service 手动启停。'
    fi
    if [ "$service_kind" != cron ]; then cron_update remove >/dev/null 2>&1 || :; fi
    if is_root; then
        router_hook add || return 1
        if [ -f /data/etc/crontabs/root ] && has uci; then
            uci set firewall.Lucky=include && uci set firewall.Lucky.type=script &&
            uci set firewall.Lucky.path="$install_dir/lucky-service" &&
            uci set firewall.Lucky.enabled=1 && uci commit firewall || return 1
        fi
    fi
}
start_tar() {
    case "$service_kind" in
        launchd) launchctl bootstrap system /Library/LaunchDaemons/com.lucky.daji.plist || return 1; sleep 2; running_tar ;;
        freebsd) /usr/local/etc/rc.d/lucky_daji onestart || return 1; sleep 2; running_tar ;;
        systemd) systemctl start lucky.daji.service || return 1; sleep 2; systemctl is-active lucky.daji.service >/dev/null ;;
        openwrt) /etc/init.d/lucky.daji start || return 1; sleep 3; running_tar ;;
        openrc) /etc/init.d/lucky.daji start || return 1; sleep 2; running_tar ;;
        *) "$install_dir/lucky-service" start ;;
    esac
}
core_pids() (
    target_dir=${1:-$install_dir}
    target=$target_dir/lucky
    if [ "$core_os" = darwin ]; then
        /usr/sbin/lsof -t -a -d txt "$target" 2>/dev/null || :
        exit
    fi
    if [ "$core_os" = freebsd ]; then
        procstat -b -a 2>/dev/null | awk -v exe="$target" '$NF==exe {print $1}'
        exit
    fi
    physical_dir=$(CDPATH='' cd "$target_dir" 2>/dev/null && pwd -P) || physical_dir=$target_dir
    link_reader=
    if has readlink; then
        link_reader=readlink
    elif busybox readlink /proc/$$/exe >/dev/null 2>&1; then
        link_reader=busybox
    fi
    for rp in /proc/[0-9]*/exe; do
        exe=
        case "$link_reader" in
            readlink) exe=$(readlink "$rp" 2>/dev/null) || exe= ;;
            busybox) exe=$(busybox readlink "$rp" 2>/dev/null) || exe= ;;
        esac
        case "$exe" in
            "$target"|"$target (deleted)"|"$physical_dir/lucky"|"$physical_dir/lucky (deleted)")
                rp=${rp#/proc/}; printf '%s\n' "${rp%/exe}" ;;
            ''|"$target_dir"/.install-v3-*/*|"$physical_dir"/.install-v3-*/*)
                # Keep the same fallback as the runner for stripped-down
                # firmware and old kernels without a usable procfs exe link.
                if [ -z "$exe" ]; then
                    IFS= read -r process_name 2>/dev/null < "${rp%/exe}/comm" || continue
                    [ "$process_name" = lucky ] || continue
                fi
                # A failed older installer may have replaced a still-running
                # staged inode. Require the original installed command as well.
                arg0=$(tr '\000' '\n' < "${rp%/exe}/cmdline" 2>/dev/null | head -n 1)
                case "$arg0" in "$target"|"$physical_dir/lucky")
                    rp=${rp#/proc/}; printf '%s\n' "${rp%/exe}" ;;
                esac ;;
        esac
    done
)
running_tar() {
    [ -n "$(core_pids "${1:-$install_dir}")" ]
}
select_core_archive() {
    detect_core
    # Accept common aliases explicitly supplied through --arch.
    case "$core_arch" in
        amd64) core_arch=x86_64 ;;
        aarch64) core_arch=arm64 ;;
        mips) core_arch=mips_softfloat ;;
        mipsel|mipsle) core_arch=mipsle_softfloat ;;
        mips64) core_arch=mips64_softfloat ;;
        mips64el|mips64le) core_arch=mips64le_softfloat ;;
    esac
    case "$core_arch" in x86_64|i386|arm64|armv5|armv6|armv7|riscv64|mips_softfloat|mips_hardfloat|mipsle_softfloat|mipsle_hardfloat|mips64_softfloat|mips64_hardfloat|mips64le_softfloat|mips64le_hardfloat) : ;; *) die "无效的核心架构：$core_arch。MIPS 可使用 mips_softfloat、mipsle_softfloat、mips64_softfloat 或 mips64le_softfloat。" ;; esac
    archive=lucky_${core_version}_${core_os}_${core_arch}
    [ "$product" = lucky ] || archive=${archive}_$product
    archive=$archive.tar.gz
    tar_url=$release_url/$product_dir
}
prepare_core_archive() {
    # Match the legacy installer: do not compare downloads with release hashes.
    # Check extraction here and execute the staged core before replacing it.
    select_core_work
    download_file "$tar_url" "$archive" "$work/core.tar.gz"
    # Count the actual expanded size without writing the tar yet. POSIX sh has
    # no pipefail, so record gzip's status explicitly and reject a missing result.
    : > "$work/gzip.status" || die "无法写入临时目录：$work。原程序未替换。"
    tar_bytes=$(
        if gzip -dc "$work/core.tar.gz"; then printf '0\n' > "$work/gzip.status"
        else printf '1\n' > "$work/gzip.status"; fi | wc -c
    ) || die '无法计算解压空间，原程序未替换。'
    [ "$(cat "$work/gzip.status")" = 0 ] || die '压缩包损坏或下载不完整，原程序未替换。'
    tar_kib=$(printf '%s\n' "$tar_bytes" | awk 'NF==1 && $1 ~ /^[0-9]+$/ {printf "%.0f", ($1+1023)/1024; ok=1} END {exit !ok}') || die '无法读取解压大小。'
    check_core_space
    gzip -dc "$work/core.tar.gz" > "$work/core.tar" || die "解压失败：压缩包损坏、下载不完整或临时目录空间不足（$work）。原程序未替换。"
    # Router /tmp is often RAM-backed. Release each archive as soon as its
    # replacement is complete, before extracting or running the packed core.
    rm -f "$work/core.tar.gz" || die '无法清理下载缓存，原程序未替换。'
    tar -tf "$work/core.tar" > "$work/members" 2> "$work/tar.inspect.log" || die '无法读取 tar 文件。'
    # Old BusyBox strips ../ even from its listing; it reports that on stderr.
    # Reject warnings too, before relying on the (possibly normalized) names.
    [ ! -s "$work/tar.inspect.log" ] || die 'tar 检查发现不安全路径或不兼容条目，未解压。'
    awk '/^\// || /(^|\/)\.\.($|\/)/ {bad=1} END {exit bad}' "$work/members" || die '压缩包包含不安全路径。'
    # Reject links/devices before extraction. Release archives contain files/dirs only.
    tar -tvf "$work/core.tar" > "$work/types" 2> "$work/tar.inspect.log" || die '无法检查 tar 条目。'
    [ ! -s "$work/tar.inspect.log" ] || die 'tar 检查出现警告，未解压。'
    awk 'substr($0,1,1)!="-" && substr($0,1,1)!="d" {bad=1} END {exit bad}' "$work/types" || die '压缩包包含链接或特殊文件。'
    check_space "$install_dir" "$tar_kib"
    if [ "$action" = update ]; then
        # A fixed, private staging directory also serializes script core updates.
        candidate=$install_dir/.install-v3-core-update
    else candidate=$install_dir/.install-v3-$$
    fi
    (umask 077; mkdir "$candidate") || die "无法创建暂存目录（不可写或另一次操作未结束）：$candidate"
    stage=$candidate
    (cd "$stage" && tar -xf "$work/core.tar") || die '解压失败，原程序未替换。'
    rm -f "$work/core.tar" || die '无法清理解压缓存，原程序未替换。'
    if [ ! -f "$stage/lucky" ] || [ -L "$stage/lucky" ]; then die '安装包没有有效的 lucky 核心。'; fi
    chmod 755 "$stage/lucky" || die '无法设置核心权限。'
}
label_core() {
    if has selinuxenabled && selinuxenabled; then
        # A binary installed under /etc must not run in systemd's init_t domain.
        # Keep administrator-defined executable types on existing installations.
        label=$(stat -c '%C' "$install_dir/lucky" 2>/dev/null)
        case "$label" in
            *:bin_t:*|*:*_exec_t:*) chcon --reference="$install_dir/lucky" "$1" ;;
            *) chcon -t bin_t "$1" ;;
        esac || die '无法设置核心的 SELinux 可执行文件标签，原程序未替换。'
    fi
}
install_tar() {
    find_installed_package
    if [ -n "$installed_package" ]; then
        die 'Lucky 已由系统包管理器管理，请先卸载对应软件包（保留配置），避免两套服务并存。'
    fi
    select_core_archive
    choose_dir
    say "产品：$product_dir；核心架构：$core_arch；安装目录：$install_dir"
    say "安装包：$tar_url/$archive"
    [ "$dry_run" != 1 ] || return 0
    confirm '开始安装/升级并保留配置？' || exit 0
    mkdir -p "$install_dir" || die '无法创建安装目录。'
    [ -w "$install_dir" ] || die '安装目录不可写。'
    prepare_core_archive
    label_core "$stage/lucky"
    select_service_tmpdir
    prepare_service_tmpdir || die '无法准备服务临时目录，原程序未替换。'
    # Probe with the same storage policy as the installed service, before any
    # stop/replace. The loader allocates actual backing space rather than relying
    # on a sparse file which could later SIGBUS on a small tmpfs.
    TMPDIR="$service_tmpdir" UPX_TMPDIR="$service_upx_tmpdir" "$stage/lucky" -info > "$work/core-version" 2>&1 || { cat "$work/core-version" >&2; die '核心不能在当前系统运行，原程序未替换。'; }
    had_old=0
    if [ -f "$install_dir/lucky" ]; then
        cp -p "$install_dir/lucky" "$stage/lucky.previous" || die '旧程序备份失败。'
        had_old=1
    fi
    stop_tar || die '无法停止旧服务。'
    mv "$stage/lucky" "$install_dir/lucky" || die '替换核心失败。'
    write_runner
    install_error=
    if ! setup_service; then
        install_error='服务启动项注册失败'
    elif [ "$no_start" != 1 ] && ! start_tar; then
        install_error='服务启动验证失败'
    fi
    if [ -n "$install_error" ]; then
        stop_tar || :
        if [ "$had_old" = 1 ]; then
            mv "$stage/lucky.previous" "$install_dir/lucky" || die '恢复旧核心失败，请保留安装目录。'
            [ "$no_start" = 1 ] || start_tar || :
        else
            disable_tar || :
            rm -f "$install_dir/lucky" "$install_dir/lucky-service"
        fi
        die "$install_error，已回退核心替换。请检查系统日志和 $install_dir/lucky.log。"
    fi
    mkdir -p "$(dirname "$record")" || die '无法保存安装记录。'
    printf 'directory=%s\nproduct=%s\nversion=%s\nservice=%s\n' "$install_dir" "$product" "$core_version" "$service_kind" > "$record" || die '无法保存安装记录。'
    printf '%s\n' "$product_dir" > "$install_dir/.install-v3"
    say "Lucky 安装完成：$install_dir（$service_kind）。配置和数据已保留。"
}
find_installed_package() {
    installed_package=
    if is_openwrt; then
        if has apk && apk info -e lucky >/dev/null 2>&1; then installed_package=apk; fi
        if has opkg && opkg status lucky 2>/dev/null | awk '$1=="Status:" && $NF=="installed" {found=1} END {exit !found}'; then
            [ -z "$installed_package" ] || die '同时检测到 APK 和 IPK 安装记录，请先确认实际安装方式。'
            installed_package=ipk
        fi
    fi
}
find_update_target() {
    find_installed_package
    update_package=$installed_package
    if [ -n "$update_package" ]; then
        [ -z "$existing" ] || die "同时检测到包安装和 tar 核心：$existing。拒绝选择可能错误的服务。"
        [ -z "$install_dir" ] || [ "${install_dir%/}" = /usr/bin ] || die 'APK/IPK 核心固定在 /usr/bin/lucky，--dir 不是业务配置目录。'
        install_dir=/usr/bin
        case "$update_package" in
            apk) apk info -L lucky > "$work/installed.files" || die '无法读取 APK 文件记录。' ;;
            ipk) opkg files lucky > "$work/installed.files" || die '无法读取 IPK 文件记录。' ;;
        esac
        awk '$0=="/usr/bin/lucky" || $0=="usr/bin/lucky" {found=1} END {exit !found}' "$work/installed.files" || die '包管理器记录的核心路径不是 /usr/bin/lucky，请勿盲目覆盖。'
    else
        [ -n "$install_dir" ] || install_dir=$existing
        install_dir=${install_dir%/}
        safe_dir "$install_dir" || die '未找到已安装核心，可使用 --dir 指定原核心所在目录。'
        if [ -n "$existing" ]; then
            known_dir=$(CDPATH='' cd "$existing" && pwd -P) || die '已有安装目录无法访问。'
            requested_dir=$(CDPATH='' cd "$install_dir" && pwd -P) || die '指定的核心目录不存在。'
            [ "$known_dir" = "$requested_dir" ] || die "已存在安装：$existing。拒绝更新其他目录的核心。"
        fi
    fi
    update_service_bin=$install_dir/lucky
    install_dir=$(CDPATH='' cd "$install_dir" && pwd -P) || die '核心目录无法访问。'
    safe_dir "$install_dir" || die '核心实际目录不是安全的绝对路径。'
    [ -f "$install_dir/lucky" ] && [ ! -L "$install_dir/lucky" ] || die '原核心不存在或是符号链接，未执行更新。'
    if [ -n "$update_package" ] && [ "$dry_run" != 1 ]; then
        is_root || die '更新 OpenWrt APK/IPK 核心需要 root。'
    fi
}
systemd_core_matches() {
    # Use loaded unit properties, including vendor units and local drop-ins.
    awk -v exe="$install_dir/lucky" -v alias="$update_service_bin" '
        $0=="LoadState=loaded" {loaded=1}
        /^ExecStart=/ && (index($0,"path=" exe " ;") || index($0,"path=" alias " ;")) {matched=1}
        END {exit !(loaded && matched)}' "$1"
}
update_script_matches() {
    grep -F "$install_dir/lucky" "$1" >/dev/null 2>&1 ||
        grep -F "$update_service_bin" "$1" >/dev/null 2>&1 ||
        { [ "$existing" = "$install_dir" ] && [ -f "$install_dir/scripts/luckyservice" ] && cmp -s "$1" "$install_dir/scripts/luckyservice"; }
}
select_update_service() {
    update_backend=none
    if is_root; then
        if [ -n "$update_package" ]; then
            [ -x /etc/init.d/lucky ] || die '已安装包缺少 /etc/init.d/lucky，未停止原进程。'
            update_backend=package
        elif [ "$core_os" = darwin ] && [ -f /Library/LaunchDaemons/com.lucky.daji.plist ]; then
            job_label=$(/usr/libexec/PlistBuddy -c 'Print :Label' /Library/LaunchDaemons/com.lucky.daji.plist 2>/dev/null) || job_label=
            [ "$job_label" = com.lucky.daji ] || die '现有 launchd 启动项的 Label 不匹配。'
            job_bin=$(/usr/libexec/PlistBuddy -c 'Print :ProgramArguments:0' /Library/LaunchDaemons/com.lucky.daji.plist 2>/dev/null) || job_bin=
            [ -n "$job_bin" ] || job_bin=$(/usr/libexec/PlistBuddy -c 'Print :Program' /Library/LaunchDaemons/com.lucky.daji.plist 2>/dev/null) || job_bin=
            [ "$job_bin" = "$install_dir/lucky" ] || [ "$job_bin" = "$update_service_bin" ] || die '现有 launchd 启动项不属于所选核心。'
            launchctl print-disabled system > "$work/update.disabled" || die '无法读取原 launchd 自启状态，未停止原进程。'
            if awk '/^[ \t]*"com\.lucky\.daji" => (true|disabled),?[ \t]*$/ {found=1} END {exit !found}' "$work/update.disabled"; then update_launchd_disabled=1; fi
            update_backend=launchd
        elif [ "$core_os" = freebsd ] && [ -x /usr/local/etc/rc.d/lucky_daji ]; then
            update_script_matches /usr/local/etc/rc.d/lucky_daji || die '现有 FreeBSD 启动项不属于所选核心。'
            update_backend=freebsd
        elif [ -d /run/systemd/system ] && has systemctl; then
            systemctl show -p LoadState -p ExecStart lucky.daji.service > "$work/update.service" 2>/dev/null || :
            if grep '^LoadState=loaded$' "$work/update.service" >/dev/null; then
                systemd_core_matches "$work/update.service" || die '现有 systemd 启动项不属于所选核心或使用了自定义包装程序。'
                update_backend=systemd
            fi
        fi
        if [ "$update_backend" = none ] && [ -x /etc/init.d/lucky.daji ]; then
            update_script_matches /etc/init.d/lucky.daji || die '现有 init.d 启动项不属于所选核心。'
            update_backend=initd
        fi
    fi
    if [ "$update_backend" = none ] && [ -x "$install_dir/lucky-service" ]; then update_backend=runner; fi
    update_was_running=0
    update_pids=$(core_pids)
    if [ -n "$update_pids" ]; then
        update_was_running=1
        [ "$update_backend" != none ] || die '核心正在运行，但无法确认原启动方式。请先按原方式停止，再更新核心；脚本不会猜测启动参数。'
        [ "$(printf '%s\n' "$update_pids" | wc -l | tr -d ' ')" = 1 ] || die '检测到多个同路径核心进程，请先按原方式停止再更新，避免丢失不同实例的启动参数。'
        case "$update_backend" in
            systemd)
                owner_pid=$(systemctl show -p MainPID lucky.daji.service | sed -n 's/^MainPID=//p')
                [ "$owner_pid" = "$update_pids" ] || die '运行中的核心不属于现有 systemd 服务，请先按原方式停止再更新。' ;;
            launchd)
                owner_pid=$(launchctl print system/com.lucky.daji 2>/dev/null | awk '$1=="pid" && $2=="=" {print $3; exit}')
                [ "$owner_pid" = "$update_pids" ] || die '运行中的核心不属于现有 launchd 服务，请先按原方式停止再更新。' ;;
        esac
    fi
}
stop_update_service() {
    case "$update_backend" in
        package) /etc/init.d/lucky stop || return 1 ;;
        launchd)
            if launchctl print system/com.lucky.daji >/dev/null 2>&1; then launchctl bootout system/com.lucky.daji || return 1; fi ;;
        freebsd)
            if /usr/local/etc/rc.d/lucky_daji onestatus >/dev/null 2>&1; then /usr/local/etc/rc.d/lucky_daji onestop || return 1; fi ;;
        systemd) systemctl stop lucky.daji.service || return 1 ;;
        initd) /etc/init.d/lucky.daji stop || return 1 ;;
        runner) "$install_dir/lucky-service" stop || return 1 ;;
    esac
    for pid in $(core_pids); do kill "$pid" 2>/dev/null || :; done
    wait_count=0
    while running_tar; do
        [ "$wait_count" -lt 15 ] || return 1
        sleep 1; wait_count=$((wait_count + 1))
    done
}
start_update_launchd() {
    # launchd cannot bootstrap a disabled job, even if it was previously running.
    # Temporarily permit bootstrap, then restore the original autostart policy.
    if [ "$update_launchd_disabled" = 1 ]; then
        update_launchd_temporary_enable=1
        launchctl enable system/com.lucky.daji || return 1
    fi
    launchctl bootstrap system /Library/LaunchDaemons/com.lucky.daji.plist
    launchd_start_result=$?
    if [ "$update_launchd_temporary_enable" = 1 ]; then
        launchctl disable system/com.lucky.daji || return 1
        update_launchd_temporary_enable=0
    fi
    return "$launchd_start_result"
}
start_update_service() {
    case "$update_backend" in
        package) /etc/init.d/lucky start || return 1 ;;
        launchd) start_update_launchd || return 1 ;;
        freebsd) /usr/local/etc/rc.d/lucky_daji onestart || return 1 ;;
        systemd) systemctl start lucky.daji.service || return 1 ;;
        initd) /etc/init.d/lucky.daji start || return 1 ;;
        runner) "$install_dir/lucky-service" start || return 1 ;;
        *) return 1 ;;
    esac
    wait_count=0; stable_count=0
    while [ "$wait_count" -lt 20 ]; do
        if running_tar; then stable_count=$((stable_count + 1)); else stable_count=0; fi
        [ "$stable_count" -lt 3 ] || return 0
        sleep 1; wait_count=$((wait_count + 1))
    done
    return 1
}
core_metadata() {
    if has stat; then
        case "$core_os" in
            freebsd|darwin) stat -f '%u %g %Lp' "$1" ;;
            *) stat -c '%u %g %a' "$1" ;;
        esac
    else
        # Some OpenWrt BusyBox builds omit stat. POSIX ls -n keeps UID/GID numeric.
        # Only permission/UID/GID fields of a fixed, validated path are inspected.
        # shellcheck disable=SC2012
        ls -ldn "$1" | awk '
            $1 ~ /^-/ && $3 ~ /^[0-9]+$/ && $4 ~ /^[0-9]+$/ {
                special=0; mode=""
                for (i=1; i<=3; i++) {
                    digit=0; offset=2+(i-1)*3
                    if (substr($1,offset,1)=="r") digit+=4
                    if (substr($1,offset+1,1)=="w") digit+=2
                    x=substr($1,offset+2,1)
                    if (x=="x" || x=="s" || x=="t") digit++
                    if (i<3 && (x=="s" || x=="S")) special+=(i==1 ? 4 : 2)
                    if (i==3 && (x=="t" || x=="T")) special++
                    mode=mode digit
                }
                mode=special mode; sub(/^0+/,"",mode); if (mode=="") mode="0"
                print $3, $4, mode; found=1
            }
            END {exit !found}'
    fi
}
prepare_core_replacement() {
    update_original_hash=$(hash_file "$install_dir/lucky") || die '无法校验原核心。'
    # A hard link retains the old inode, permissions, ACLs and extended attributes.
    ln "$install_dir/lucky" "$stage/lucky.previous" || die '旧核心备份失败，未停止原服务。'
    metadata=$(core_metadata "$install_dir/lucky") || die '无法读取原核心权限。'
    update_mode=$(printf '%s\n' "$metadata" | awk 'NF==3 && $3 ~ /^[0-7]+$/ {print $3}')
    [ -n "$update_mode" ] || die '原核心权限格式无效。'
    replacement_kib=$(wc -c < "$install_dir/lucky" > "$work/old.size" && wc -c < "$stage/lucky" > "$work/new.size" &&
        awk '{if ($1>largest) largest=$1} END {printf "%.0f", (largest+1023)/1024}' "$work/old.size" "$work/new.size") || die '无法读取核心大小。'
    check_space "$install_dir" "$replacement_kib"
    if ! { cp -p "$install_dir/lucky" "$stage/lucky.new" && cp "$stage/lucky" "$stage/lucky.new" && chmod "$update_mode" "$stage/lucky.new"; }; then
        die '无法准备核心替换文件，未停止原服务。'
    fi
    [ "$(core_metadata "$stage/lucky.new")" = "$metadata" ] || die '无法保留原核心所有者和权限，未停止原服务。'
    label_core "$stage/lucky.new"
    if [ "$core_os" = Linux ] && has getcap; then
        getcap "$install_dir/lucky" > "$work/core.capabilities" || die '无法读取原核心 capabilities。'
        capabilities=$(awk -v exe="$install_dir/lucky" '$1==exe {$1=""; sub(/^[ \t]+/,""); print}' "$work/core.capabilities")
        if [ -n "$capabilities" ]; then
            if ! { has setcap && setcap "$capabilities" "$stage/lucky.new"; }; then die '无法保留原核心 capabilities，未停止原服务。'; fi
        fi
    fi
    rm -f "$stage/lucky" || die '无法清理解压的核心副本，未停止原服务。'
    "$stage/lucky.new" -info > "$work/core-version" 2>&1 || { cat "$work/core-version" >&2; die '新核心不能在当前目录和系统运行，未停止原服务。'; }
}
rollback_core_update() {
    if [ "$update_replaced" = 1 ]; then
        if [ "$update_was_running" = 1 ] || running_tar; then stop_update_service || return 1; fi
        ln "$stage/lucky.previous" "$stage/lucky.restore" && mv "$stage/lucky.restore" "$install_dir/lucky" || return 1
        update_replaced=0
    fi
    if [ "$update_was_running" = 1 ] && ! running_tar; then start_update_service || return 1; fi
    update_pending=0
    err '已恢复旧核心及原运行状态。'
}
commit_core_update() {
    [ "$(hash_file "$install_dir/lucky")" = "$update_original_hash" ] || die '原核心在准备期间发生变化，可能存在另一次升级，未执行替换。'
    update_pending=1
    if [ "$update_was_running" = 1 ]; then stop_update_service || die '停止原服务失败，正在恢复原运行状态。'; fi
    [ "$(hash_file "$install_dir/lucky")" = "$update_original_hash" ] || die '原核心在停止期间发生变化，未执行替换。'
    # Set the rollback state before rename, so a signal after rename is recoverable.
    update_replaced=1
    mv "$stage/lucky.new" "$install_dir/lucky" || die '替换核心失败，正在回退。'
    if [ "$update_was_running" = 1 ]; then
        start_update_service || die '新核心未能稳定运行，正在恢复旧核心和原服务。'
    fi
    update_pending=0
}
update_core() {
    find_update_target
    select_update_service
    select_core_archive
    say "只更新核心：$install_dir/lucky；产品：$product_dir；架构：$core_arch；原启动方式：$update_backend"
    say "安装包：$tar_url/$archive"
    if [ -n "$update_package" ]; then
        say "检测到 OpenWrt $update_package 安装：仅替换二进制，包版本记录不变。以后升级/重装软件包可能覆盖此核心。"
    fi
    say '保留现有启动项、启动参数、自启设置、UCI、LuCI、语言包和业务配置；原来停止的仍保持停止。'
    [ "$dry_run" != 1 ] || return 0
    confirm '开始更新核心？' || exit 0
    [ -w "$install_dir" ] || die '核心所在目录不可写，未停止原服务。'
    prepare_core_archive
    prepare_core_replacement
    commit_core_update
    say "核心更新完成：$install_dir/lucky。原服务与配置未重建。"
}

disable_tar() {
    stop_tar || return 1
    if is_root; then
        if [ "$core_os" = darwin ]; then
            launchctl disable system/com.lucky.daji || return 1
            rm -f /Library/LaunchDaemons/com.lucky.daji.plist || return 1
        fi
        if [ "$core_os" = freebsd ] && [ -f /usr/local/etc/rc.d/lucky_daji ]; then
            sysrc -x lucky_daji_enable || return 1
            rm -f /usr/local/etc/rc.d/lucky_daji /var/run/lucky_daji.pid || return 1
        fi
        if [ -d /run/systemd/system ] && has systemctl; then
            systemctl disable lucky.daji.service 2>/dev/null || :
            rm -f /etc/systemd/system/lucky.daji.service || return 1
            # The historical installer used the vendor directory. Remove only
            # units whose executable belongs to the installation being removed.
            for legacy_unit in /usr/lib/systemd/system/lucky.daji.service /lib/systemd/system/lucky.daji.service; do
                [ -f "$legacy_unit" ] || continue
                if awk -v exe="$install_dir/lucky" '$0=="ExecStart=" exe || index($0,"ExecStart=" exe " ")==1 {found=1} END {exit !found}' "$legacy_unit"; then
                    rm -f "$legacy_unit" || return 1
                fi
            done
            systemctl daemon-reload || return 1
        fi
        if [ -x /etc/init.d/lucky.daji ]; then
            if is_openwrt; then /etc/init.d/lucky.daji disable || return 1
            elif has rc-update; then rc-update del lucky.daji default || return 1; fi
            rm -f /etc/init.d/lucky.daji || return 1
        fi
        router_hook remove || return 1
        if has uci; then
            case "$(uci -q get firewall.Lucky.path)" in
                "$install_dir/lucky-service"|"$install_dir/scripts/misnap_init.sh")
                    uci delete firewall.Lucky && uci commit firewall || return 1 ;;
            esac
        fi
    fi
    cron_update remove >/dev/null 2>&1 || :
}
prepare_apk_trust() {
    apk_signed=0
    apk_public_key=lucky-apk-public.pem
    # An unavailable directory or an advertised-but-missing key is an error,
    # never evidence that this is an unsigned historical release.
    list_remote "$release_url/apk" "$work/apk-files"
    apk_key_count=$(awk -v key="$apk_public_key" '$2==key {n++} END {print n+0}' "$work/shared.sums")
    if [ "$apk_key_count" = 0 ] && ! grep -Fx "$apk_public_key" "$work/apk-files" >/dev/null; then
        [ -z "$apk_key_sha256" ] || die '指定了 APK 公钥指纹，但此版本没有公钥；拒绝降级安装。'
        say '此旧版 APK 目录没有公钥，使用未签名兼容安装。'
        return
    fi
    [ "$apk_key_count" = 1 ] || die 'APK 公钥在 SHA256SUMS 中缺失或重复，拒绝降级安装。'
    download_file "$release_url/apk" "$apk_public_key" "$work/$apk_public_key"
    [ "$(wc -c < "$work/$apk_public_key" | tr -d ' ')" -le 4096 ] || die 'APK 公钥文件过大。'
    apk_public_hash=$(hash_file "$work/$apk_public_key") || die '无法校验 APK 公钥。'
    apk_expected_hash=${apk_key_sha256:-$apk_default_key_sha256}
    [ "$apk_public_hash" = "$apk_expected_hash" ] || die 'APK 公钥指纹不匹配。请核对发布方公布的指纹；第三方软件源可使用 --apk-key-sha256 指定，不会跳过验签。'
    mkdir "$work/apk-keys" || die '无法创建 APK 验签目录。'
    cp "$work/$apk_public_key" "$work/apk-keys/$apk_public_key" || die '无法准备 APK 公钥。'
    # Verify all three packages against only the selected release key, before
    # importing trust, resolving dependencies or stopping the current service.
    apk --keys-dir "$work/apk-keys" verify "$work/lucky.apk" "$work/luci.apk" "$work/lang.apk" || die 'APK 签名或内容校验失败，未停止当前服务；不会改用未签名模式。'
    import_apk_public_key
    apk_signed=1
    say "三个 APK 验签通过，已导入公钥：$apk_public_hash"
}
import_apk_public_key() {
    mkdir -p /etc/apk/keys || die '无法创建系统 APK 公钥目录。'
    apk_installed_key=/etc/apk/keys/lucky-release-$apk_public_hash.pem
    if [ -e "$apk_installed_key" ] || [ -L "$apk_installed_key" ]; then
        [ ! -L "$apk_installed_key" ] && cmp -s "$work/$apk_public_key" "$apk_installed_key" || die '系统中同名 APK 公钥内容不同，未覆盖。'
    else
        (set -C; cat "$work/$apk_public_key" > "$apk_installed_key") || die '导入 APK 公钥失败。'
        chmod 644 "$apk_installed_key" || die '设置 APK 公钥权限失败。'
    fi
}
apk_add_selected() {
    if [ "$apk_signed" = 1 ]; then apk add "$@"
    else apk --allow-untrusted add "$@"
    fi
}
install_apk() {
    say "OpenWrt 架构：$apk_arch；产品：$product"
    printf '  %s\n' "$core_apk" "$luci_apk" "$lang_apk"
    [ "$dry_run" != 1 ] || return 0
    is_root || die '安装 OpenWrt APK 需要 root。'
    [ -z "$existing" ] || die "检测到 tar 安装：$existing。请先通过本脚本卸载旧程序（保留配置），再安装 APK；APK 配置目录可在 LuCI 中指定。"
    confirm '安装以上三个 APK 并启用 Lucky 服务？' || exit 0
    download_file "$release_url/apk/$product" "$core_apk" "$work/lucky.apk"
    download_file "$release_url/apk" "$luci_apk" "$work/luci.apk"
    download_file "$release_url/apk" "$lang_apk" "$work/lang.apk"
    prepare_apk_trust
    # Do not force architecture, overwrite unrelated packages or upgrade the OS.
    if ! apk_add_selected --simulate "$work/lucky.apk" "$work/luci.apk" "$work/lang.apk"; then
        say '尝试刷新系统 APK 索引以解析依赖。'
        apk update || die '更新 APK 索引失败，未停止当前服务。'
        apk_add_selected --simulate "$work/lucky.apk" "$work/luci.apk" "$work/lang.apk" || die 'APK 依赖或安装预检查失败，未停止当前服务。'
    fi
    if [ -x /etc/init.d/lucky ]; then /etc/init.d/lucky stop || die '无法停止 Lucky 服务。'; fi
    if ! apk_add_selected "$work/lucky.apk" "$work/luci.apk" "$work/lang.apk"; then
        [ ! -x /etc/init.d/lucky ] || /etc/init.d/lucky start || :
        die 'APK 安装失败，请检查上述包管理器信息；未改用 tar 覆盖安装。'
    fi
    for package in lucky luci-app-lucky luci-i18n-lucky-zh-cn; do
        apk info -e "$package" >/dev/null 2>&1 || die "APK 未成功安装：$package"
    done
    /etc/init.d/lucky enable || die 'APK 已安装，但设置开机启动失败。'
    if [ "$no_start" != 1 ]; then
        if ! { uci set 'lucky.@lucky[0].enabled=1' && uci commit lucky && /etc/init.d/lucky start; }; then die 'APK 已安装，但服务启动失败。'; fi
        sleep 3
        running_tar /usr/bin || die 'APK 已安装，但 Lucky 没有运行，请查看 logread。'
    else
        /etc/init.d/lucky stop || die 'APK 已安装，但停止服务失败。'
    fi
    printf 'product=%s\nversion=%s\narchitecture=%s\n' "$product" "$core_version" "$apk_arch" > /etc/lucky-install-v3-apk
    say 'Lucky 核心、LuCI 插件、中文语言包安装完成。'
}
install_ipk() {
    say "OpenWrt 架构：$ipk_arch；产品：$product"
    printf '  %s\n' "$core_ipk" "$luci_ipk" "$lang_ipk"
    [ "$dry_run" != 1 ] || return 0
    is_root || die '安装 OpenWrt IPK 需要 root。'
    [ -z "$existing" ] || die "检测到 tar 安装：$existing。请先通过本脚本卸载旧程序（保留配置），再安装 IPK；IPK 配置目录可在 LuCI 中指定。"
    confirm '安装以上三个 IPK 并启用 Lucky 服务？' || exit 0
    download_file "$release_url/ipk/$product" "$core_ipk" "$work/lucky.ipk"
    download_file "$release_url/ipk" "$luci_ipk" "$work/luci.ipk"
    download_file "$release_url/ipk" "$lang_ipk" "$work/lang.ipk"
    # Reinstall the three explicitly selected local packages so products with
    # identical names/versions can be switched. Keep opkg conffile handling;
    # never force dependencies, architectures, overwrites or system upgrades.
    if ! opkg --noaction --force-reinstall install "$work/lucky.ipk" "$work/luci.ipk" "$work/lang.ipk"; then
        say '尝试刷新系统 IPK 索引以解析依赖。'
        opkg update || die '更新 IPK 索引失败，未停止当前服务。'
        opkg --noaction --force-reinstall install "$work/lucky.ipk" "$work/luci.ipk" "$work/lang.ipk" || die 'IPK 依赖或安装预检查失败，未停止当前服务。'
    fi
    ipk_was_running=0
    if running_tar /usr/bin; then ipk_was_running=1; fi
    if [ -x /etc/init.d/lucky ]; then /etc/init.d/lucky stop || die '无法停止 Lucky 服务。'; fi
    if ! opkg --force-reinstall install "$work/lucky.ipk" "$work/luci.ipk" "$work/lang.ipk"; then
        [ "$ipk_was_running" != 1 ] || { [ ! -x /etc/init.d/lucky ] || /etc/init.d/lucky start || :; }
        die 'IPK 安装失败，请检查上述包管理器信息；未改用 tar 覆盖安装。'
    fi
    for package in lucky luci-app-lucky luci-i18n-lucky-zh-cn; do
        opkg status "$package" 2>/dev/null | awk '$1=="Status:" && $NF=="installed" {found=1} END {exit !found}' || die "IPK 未成功安装：$package"
    done
    /etc/init.d/lucky enable || die 'IPK 已安装，但设置开机启动失败。'
    if [ "$no_start" != 1 ]; then
        if ! { uci set 'lucky.@lucky[0].enabled=1' && uci commit lucky && /etc/init.d/lucky start; }; then die 'IPK 已安装，但服务启动失败。'; fi
        sleep 3
        running_tar /usr/bin || die 'IPK 已安装，但 Lucky 没有运行，请查看 logread。'
    else
        /etc/init.d/lucky stop || die 'IPK 已安装，但停止服务失败。'
    fi
    printf 'product=%s\nversion=%s\narchitecture=%s\n' "$product" "$core_version" "$ipk_arch" > /etc/lucky-install-v3-ipk
    say 'Lucky 核心、LuCI 插件、中文语言包安装完成。'
}
uninstall() {
    find_installed_package
    if [ -n "$installed_package" ]; then
        is_root || die '卸载 APK/IPK 需要 root。'
        confirm "卸载 Lucky $installed_package 软件包（保留业务配置目录）？" || exit 0
        /etc/init.d/lucky stop || die '停止服务失败。'
        /etc/init.d/lucky disable || die '禁用服务失败。'
        if [ "$installed_package" = apk ]; then
            apk del luci-i18n-lucky-zh-cn luci-app-lucky lucky || die 'APK 卸载失败。'
            rm -f /etc/lucky-install-v3-apk
        else
            packages=
            for package in luci-i18n-lucky-zh-cn luci-app-lucky lucky; do
                if opkg status "$package" 2>/dev/null | awk '$1=="Status:" && $NF=="installed" {found=1} END {exit !found}'; then packages="$packages $package"; fi
            done
            # Only the fixed package names above are split into arguments.
            # shellcheck disable=SC2086
            opkg remove $packages || die 'IPK 卸载失败。'
            rm -f /etc/lucky-install-v3-ipk
        fi
    else
        [ -n "$install_dir" ] || install_dir=$existing
        if ! safe_dir "$install_dir" || [ ! -f "$install_dir/lucky" ]; then die '未找到有效安装目录，可使用 --dir 指定。'; fi
        [ -z "$existing" ] || [ "$existing" = "$install_dir" ] || die "已存在安装：$existing。拒绝移除其他目录的服务。"
        confirm "卸载 $install_dir 中的 Lucky 程序和启动项（保留配置及数据）？" || exit 0
        disable_tar || die '停止服务或移除启动项失败，未删除核心。'
        rm -f "$install_dir/lucky" "$install_dir/lucky-service" "$install_dir/lucky.pid" "$install_dir/.install-v3" "$record" || die '启动项已移除，但程序文件删除失败，请检查目录权限。'
    fi
    say 'Lucky 已卸载，业务配置和数据保留。'
}
usage() {
    cat <<'EOF'
用法：sh install_v3.sh <发布站根 URL> [选项]
  --version v3.1.0       选择线上版本目录
  --product lucky       产品名称或完整版本产品目录
  --method tar|apk|ipk  明确选择安装方式；省略则根据发布资源交互选择
  --dir /etc/lucky.daji tar 安装目录；更新时为原核心所在目录
  --arch x86_64         tar 核心架构覆盖；APK/IPK 始终使用系统包架构
  --apk-key-sha256 HEX   第三方 APK 公钥文件的可信 SHA256；指定后必须有公钥并验签
  --yes                 确认操作；安装需版本、产品、方式，更新只需版本和产品
  --no-start            安装并注册服务，完成后保持停止状态
  --dry-run             只检查选择和安装计划，不安装
  --update              仅更新已有核心，保留原服务、配置和运行状态（支持 APK/IPK）
  --uninstall           卸载程序，保留配置和数据
EOF
}
main() {
    while [ "$#" -gt 0 ]; do
        case "$1" in
            --version|--product|--method|--dir|--arch|--apk-key-sha256)
                [ "$#" -ge 2 ] || die "参数 $1 缺少值。"
                case "$1" in --version) release=$2 ;; --product) product=$2 ;; --method) method=$2 ;; --dir) install_dir=$2 ;; --arch) core_arch=$2 ;; --apk-key-sha256) apk_key_specified=1; apk_key_sha256=$(printf '%s' "$2" | tr 'A-F' 'a-f') ;; esac
                shift 2 ;;
            --yes) assume_yes=1; shift ;; --no-start) no_start=1; shift ;; --dry-run) dry_run=1; shift ;;
            --update|--uninstall)
                [ -z "$action" ] || die '--update 和 --uninstall 不能重复或同时指定。'
                action=${1#--}; shift ;;
            --help|-h) usage; return ;;
            http://*|https://*) [ -z "$base_url" ] || die '只能指定一个 URL。'; base_url=${1%/}; shift ;;
            *) die "未知参数：$1" ;;
        esac
    done
    case "$method" in ''|tar|apk|ipk) : ;; *) die '--method 只能为 tar、apk 或 ipk。' ;; esac
    if [ "$apk_key_specified" = 1 ]; then
        [ "${#apk_key_sha256}" = 64 ] || die '--apk-key-sha256 必须为 64 位十六进制。'
        case "$apk_key_sha256" in *[!0-9a-f]*) die '--apk-key-sha256 必须为 64 位十六进制。' ;; esac
        [ "$action" != update ] && [ "$action" != uninstall ] && [ "$method" = apk ] || die '--apk-key-sha256 需要 --method apk，不能用于更新核心或卸载。'
    fi
    if [ "$action" = update ]; then
        case "$method" in apk|ipk) die '--update 从 tar.gz 提取核心，不安装 APK/IPK；请省略 --method。' ;; esac
        [ "$no_start" != 1 ] || die '--update 保留原运行状态，不能与 --no-start 同时使用。'
    fi
    case "$(uname -s)" in
        Linux) core_os=Linux ;;
        FreeBSD) core_os=freebsd ;;
        Darwin) core_os=darwin ;;
        *) die '本脚本支持 Linux、FreeBSD 和 macOS；其他系统尚未适配原生服务管理。' ;;
    esac
    if [ "$core_os" = darwin ] && [ "$dry_run" != 1 ]; then
        is_root || die 'macOS 安装/更新/卸载需要 root，请使用 sudo sh install_v3.sh 执行。'
        has launchctl && has plutil && [ -x /usr/sbin/lsof ] || die 'macOS 缺少 launchctl、plutil 或 lsof。'
    fi
    make_work
    find_existing
    if [ -z "$action" ] && [ -z "$release$product$method" ] && [ "$assume_yes" != 1 ]; then
        printf '%s\n' '安装/升级 Lucky' '只更新 Lucky 核心（保留现有服务）' '卸载 Lucky（保留配置）' > "$work/actions"
        choose "$work/actions" '请选择操作'
        [ "$selected" != '卸载 Lucky（保留配置）' ] || action=uninstall
        [ "$selected" != '只更新 Lucky 核心（保留现有服务）' ] || action=update
    fi
    if [ "$action" = uninstall ]; then
        [ "$dry_run" != 1 ] || die '--dry-run 不用于卸载。'
        uninstall; return
    fi
    [ -n "$base_url" ] || { usage; die '请提供发布站根 URL。'; }
    has curl || has wget || [ -x /usr/bin/fetch ] || die '需要 curl、wget 或 FreeBSD fetch。'
    if [ "$assume_yes" = 1 ]; then
        if [ -z "$release" ] || [ -z "$product" ]; then die '--yes 需要明确指定 --version、--product。'; fi
        [ "$action" = update ] || [ -n "$method" ] || die '安装时 --yes 还需要指定 --method。'
    fi
    select_release
    if [ "$action" = update ]; then update_core; return; fi
    select_method
    case "$method" in apk) install_apk ;; ipk) install_ipk ;; *) install_tar ;; esac
}

if [ "${LUCKY_INSTALL_LIBRARY:-0}" != 1 ]; then main "$@"; fi
