#!/bin/bash
# Naixi Plugin Manager v3
NAIXI_DIR="/etc/log/naixi"
IKPKG_DIR="/tmp/ikpkg"
NAIXI_CONF="$NAIXI_DIR/.config"
mkdir -p "$NAIXI_DIR"

usage() {
    echo "Naixi Plugin Manager"
    echo ""
    local level=$(cat "$NAIXI_CONF/ikuaiyun_level" 2>/dev/null || echo "2")
    echo "云平台控制: Level $level"
    if [ -d "$NAIXI_DIR/openwrt-root/bin" ]; then
        echo "musl兼容层: ✓ 已初始化 ($(du -sh $NAIXI_DIR/openwrt-root 2>/dev/null | cut -f1))"
    else
        echo "musl兼容层: ✗ 未安装"
    fi
    if which opkg >/dev/null 2>&1; then
        echo "opkg原生环境: ✓ 已初始化 ($(opkg -v 2>/dev/null | head -1))"
    else
        echo "opkg原生环境: ✗ 未安装"
    fi
    echo ""
    echo "插件管理:"
    echo "  naixi list                 列出所有插件"
    echo "  naixi install <file|url>   安装插件(tar.gz)"
    echo "  naixi enable <name>        启用插件"
    echo "  naixi disable <name>       禁用插件"
    echo "  naixi remove <name>        卸载并删除插件"
    echo "  naixi status <name>        查看插件状态"
    echo "  naixi ipv6 [num]           查看/设置IPv6多线数量"
    echo "  naixi ikuaiyun [0|1|2]     云平台控制等级"
    echo "    0 = 正常(仅防格式化/强制升级)"
    echo "    1 = 采集/验证阻断，云平台可用"
    echo "    2 = 全阻断(默认)"
    echo ""
    echo "OpenWrt兼容层:"
    echo "  naixi opkg install <包名>  安装OpenWrt包(原生运行)"
    echo "  naixi opkg update          更新包列表"
    echo "  naixi opkg list            列出可用包"
    echo "  naixi ipk <file|url>       安装本地ipk包"
    if [ -d "$NAIXI_DIR/openwrt-root/bin" ]; then
        echo "  naixi openwrt shell         进入 musl 环境 shell"
        echo "  naixi openwrt clean         清理 chroot 内包 (安全)"
        echo "  naixi openwrt clean --force  同时清 host 侧 opkg 包 (可能影响系统)"
        echo "  naixi openwrt uninit         卸载 musl + opkg 二进制，保留 host 包"
        echo "  naixi openwrt uninit --force 完全卸载（会删 opkg-root，可能弄坟系统）"
    else
        echo "  naixi openwrt init [<url>]    一键安装兼容层（opkg + musl chroot）"
        echo "                                      可传自定义 url 使用镜像源"
    fi
}

do_list() {
    echo "=== 已安装组件 ==="
    local found=0
    # Naixi插件
    for dir in $NAIXI_DIR/*/; do
        [ -d "$dir" ] || continue
        name=$(basename "$dir")
        [ "$name" = "lost+found" -o "$name" = ".config" -o "$name" = "openwrt-root" -o "$name" = "opkg-root" -o "$name" = "overlay" -o "$name" = "musl-libs" -o "$name" = "opkg-cache" -o "$name" = "cache" ] && continue
        found=1
        local ver=""
        [ -f "$dir/version" ] && ver=" v$(cat $dir/version)"
        if [ -f "$dir/.disabled" ]; then echo "  ✗ $name$ver  [naixi]  已禁用"
        elif [ -d "$IKPKG_DIR/$name" ]; then echo "  ✓ $name$ver  [naixi]  运行中"
        else echo "  - $name$ver  [naixi]  未加载"; fi
    done
    # PMD插件
    for dir in $IKPKG_DIR/*/; do
        [ -d "$dir" ] || continue
        name=$(basename "$dir")
        # 跳过已在naixi中显示的
        [ -d "$NAIXI_DIR/$name" ] && continue
        found=1
        local ver=""
        [ -f "$dir/version" ] && ver=" v$(cat $dir/version)"
        echo "  ✓ $name$ver  [pmd]  运行中"
    done
    # opkg原生包(跳过opkg自身，它已在[naixi]里)
    if which opkg >/dev/null 2>&1; then
        opkg list-installed 2>/dev/null | while read pkg dash ver; do
            [ "$pkg" = "opkg" ] && continue
            found=1
            local status="已安装"
            pidof "$pkg" >/dev/null 2>&1 && status="运行中"
            echo "  · $pkg $ver  [opkg]  $status"
        done
    fi
    # musl兼容层包
    if [ -d "$NAIXI_DIR/openwrt-root/bin" ]; then
        local chroot_count=$(chroot $NAIXI_DIR/openwrt-root /bin/opkg list-installed 2>/dev/null | wc -l)
        if [ "$chroot_count" -gt 0 ]; then
            chroot $NAIXI_DIR/openwrt-root /bin/opkg list-installed 2>/dev/null | while read pkg dash ver; do
                echo "  · $pkg $ver  [musl]  已安装"
            done
        fi
    fi
    [ $found -eq 0 ] && echo "  (无组件)"
}

do_install() {
    local src="$1"
    [ -z "$src" ] && echo "用法: naixi install <url|path|file.ipk>" && exit 1
    local fname=$(basename "$src")

    # Handle .ipk files (OpenWrt packages)
    if echo "$fname" | grep -qE '\.ipk$'; then
        local tmpipk="/tmp/naixi_install.ipk"
        if echo "$src" | grep -qE "^https?://"; then
            wget -q -O "$tmpipk" "$src" || { echo "❌ 下载失败"; return 1; }
        elif [ -f "$src" ]; then
            cp "$src" "$tmpipk"
        else
            echo "❌ 文件不存在: $src"; return 1
        fi
        echo "📦 安装 ipk: $fname"
        cd /tmp && rm -f data.tar.gz control.tar.gz debian-binary
        tar xzf "$tmpipk" 2>/dev/null && tar xzf data.tar.gz -C "$NAIXI_DIR/opkg-root/" 2>/dev/null
        rm -rf "$NAIXI_DIR/opkg-root/lib/modules/"
        # Auto-generate menu.d for Lua controllers
        for ctrl in "$NAIXI_DIR/opkg-root/usr/lib/lua/luci/controller/"*.lua; do
            [ -f "$ctrl" ] || continue
            local cname=$(basename "$ctrl" .lua)
            [ "$cname" = "admin" ] && continue
            local mjson="$NAIXI_DIR/opkg-root/usr/share/luci/menu.d/luci-app-${cname}.json"
            [ -f "$mjson" ] && continue
            local ctitle=$(grep -m1 "entry.*\"" "$ctrl" 2>/dev/null | sed "s/.*\"\([^\"]*\)\".*/\1/" | head -1)
            [ -z "$ctitle" ] && ctitle="$cname"
            printf "{\"admin/services\":{\"title\":\"Services\",\"order\":40,\"action\":{\"type\":\"firstchild\"}},\"admin/services/%s\":{\"title\":\"%s\",\"order\":50,\"action\":{\"type\":\"cbi\",\"path\":\"%s/client\"},\"depends\":{\"acl\":[\"luci-app-%s\"]}}}" "$cname" "$ctitle" "$cname" "$cname" > "$mjson"
        done
        rm -f /tmp/luci-indexcache /tmp/luci-modulecache "$tmpipk"
        echo "✅ $fname 已安装。Logout+Login 查看菜单。"
        return 0
    fi

    # Handle .tar.gz files (Naixi plugins)
    local name="${fname%.tar.gz}"
    if echo "$src" | grep -qE "^https?://"; then
        echo "下载: $src"
        wget -q -O "$NAIXI_DIR/$fname" "$src" || { echo "❌ 下载失败"; exit 1; }
    elif [ -f "$src" ]; then
        echo "复制: $src"
        cp "$src" "$NAIXI_DIR/$fname"
    else
        echo "❌ 文件不存在: $src"; exit 1
    fi
    echo "解压: $fname → $name/"
    mkdir -p "$NAIXI_DIR/$name"
    tar xzf "$NAIXI_DIR/$fname" -C "$NAIXI_DIR/$name/" 2>/dev/null
    rm -f "$NAIXI_DIR/$fname"
    do_enable "$name"
}

do_enable() {
    local name="$1"
    [ -z "$name" ] && echo "用法: naixi enable <name>" && exit 1
    local dir="$NAIXI_DIR/$name"
    [ ! -d "$dir" ] && echo "❌ 插件不存在: $name" && exit 1
    [ ! -f "$dir/install.sh" ] && echo "❌ 缺少install.sh: $name" && exit 1
    rm -f "$dir/.disabled"
    export INSTALL_DIR="$IKPKG_DIR/$name"
    mkdir -p "$INSTALL_DIR"
    cp -a "$dir"/* "$INSTALL_DIR/" 2>/dev/null
    echo "启用: $name"
    cd "$INSTALL_DIR" && bash install.sh
    # 装完顺手启动 service（跟 boot 脚本一致）
    if [ -f "$INSTALL_DIR/script/${name}.sh" ]; then
        bash "$INSTALL_DIR/script/${name}.sh" start 2>/dev/null && echo "已启动服务: $name"
    fi
    echo "✅ $name 已启用"
}

do_disable() {
    local name="$1"
    [ -z "$name" ] && echo "用法: naixi disable <name>" && exit 1
    local dir="$NAIXI_DIR/$name"
    [ ! -d "$dir" ] && echo "❌ 插件不存在: $name" && exit 1
    [ -f "$IKPKG_DIR/$name/uninstall.sh" ] && {
        cd "$IKPKG_DIR/$name" && bash uninstall.sh 2>/dev/null
    }
    rm -f "/usr/ikuai/www/plugins/$name"
    rm -f "/usr/ikuai/function/${name}_"*
    rm -f "/usr/sbin/ik${name}" "/usr/sbin/$name"
    rm -rf "$IKPKG_DIR/$name"
    touch "$dir/.disabled"
    echo "✅ $name 已禁用"
}

do_remove() {
    local name="$1"
    [ -z "$name" ] && echo "用法: naixi remove <name>" && exit 1
    local dir="$NAIXI_DIR/$name"
    [ ! -d "$dir" ] && echo "❌ 插件不存在: $name" && exit 1
    do_disable "$name" 2>/dev/null
    rm -rf "$dir"
    echo "✅ $name 已彻底删除"
}

do_status() {
    local name="$1"
    [ -z "$name" ] && echo "用法: naixi status <name>" && exit 1
    local dir="$NAIXI_DIR/$name"
    [ ! -d "$dir" ] && echo "❌ 插件不存在: $name" && exit 1
    echo "=== $name ==="
    echo "持久化: $dir"
    echo "运行时: $IKPKG_DIR/$name"
    if [ -f "$dir/.disabled" ]; then echo "状态: 已禁用"
    elif [ -d "$IKPKG_DIR/$name" ]; then echo "状态: 运行中"
    else echo "状态: 未加载"; fi
    [ -f "$dir/version" ] && echo "版本: $(cat $dir/version)"
}

do_ipv6() {
    local num="$1"
    if [ -z "$num" ]; then
        echo "当前IPv6配置:"
        cat /etc/mnt/.ipv6_multi 2>/dev/null || echo "(未设置)"
        return
    fi
    echo "expires=0 num=$num enterprise=1" > /etc/mnt/.ipv6_multi
    mkdir -p "$NAIXI_CONF"
    echo "$num" > "$NAIXI_CONF/ipv6_num"
    echo "✅ IPv6多线已设为: $num"
}

# ===== 云平台控制 =====

# iptables 阻断 (二进制程序不走 /etc/hosts)
_iptables_block_collect() {
    # 仅阻断采集/验证/审计 IP，保留云平台可用
    for ip in 59.110.6.135 180.163.146.14 180.163.146.7; do
        iptables -C OUTPUT -d "$ip" -j DROP 2>/dev/null || iptables -I OUTPUT -d "$ip" -j DROP
    done
    pkill -f "coll.ikuai8.com" 2>/dev/null
    echo "[Naixi] iptables: 采集/验证IP已阻断"
}

_iptables_block_ikuai() {
    _iptables_block_collect
    # 云管理 IP: as1/as2
    for ip in 123.56.197.181 123.56.221.14; do
        iptables -C OUTPUT -d "$ip" -j DROP 2>/dev/null || iptables -I OUTPUT -d "$ip" -j DROP
    done
    pkill -f ik_rc_client 2>/dev/null
    echo "[Naixi] iptables: 云服务IP已阻断"
}

_iptables_block_ikuai_full() {
    _iptables_block_ikuai
    # DPI/routers/audit/genuine/open/download/portal/302
    for ip in 123.57.14.224 180.163.146.14 180.163.146.7 180.163.146.9 58.221.58.100 47.91.164.81 8.222.212.102; do
        iptables -C OUTPUT -d "$ip" -j DROP 2>/dev/null || iptables -I OUTPUT -d "$ip" -j DROP
    done
    echo "[Naixi] iptables: 全部ikuai8.com IP已阻断"
}

_iptables_unblock_ikuai() {
    for ip in 123.56.197.181 123.56.221.14 59.110.6.135 123.57.14.224 180.163.146.14 180.163.146.7 180.163.146.9 58.221.58.100 47.91.164.81 8.222.212.102; do
        iptables -D OUTPUT -d "$ip" -j DROP 2>/dev/null
    done
    # 恢复 webman.lua 云绑定API
    local wlua="/usr/openresty/lua/lib/webman.lua"
    if [ -f "$wlua" ] && grep -q '127.0.0.1' "$wlua" 2>/dev/null; then
        sed -i 's|http://127.0.0.1/|https://yun.ikuai8.com/api/v3/router_bind/|g' "$wlua"
        pkill -f openresty 2>/dev/null; sleep 1; /usr/sbin/openresty 2>/dev/null
    fi
    # 恢复 monitor_process.sh
    if [ -f /usr/ikuai/script/utils/monitor_process.sh ] && grep -q "NAIXI_BLOCK_RC" /usr/ikuai/script/utils/monitor_process.sh; then
        sed -i '/NAIXI_BLOCK_RC/d;/^return 0$/d' /usr/ikuai/script/utils/monitor_process.sh 2>/dev/null
    fi
    # 恢复被重命名的二进制
    for ext in naixi_disabled bak; do [ -f /usr/sbin/ik_rc_client.$ext ] && mv /usr/sbin/ik_rc_client.$ext /usr/sbin/ik_rc_client; done
    for ext in naixi_disabled bak; do [ -f /usr/sbin/dtalkd.$ext ] && mv /usr/sbin/dtalkd.$ext /usr/sbin/dtalkd; done
    echo "[Naixi] iptables: 已解除阻断"
}

_apply_level0() {
    # 先清理高级别的阻断规则
    _iptables_unblock_ikuai
    rm -f /etc/hosts.d/naixi_block 2>/dev/null
    cat /etc/hosts.d/* > /etc/hosts 2>/dev/null
    # Hook sysupgrade防远程升级
    if ! grep -q "NAIXI_PROTECT" /sbin/sysupgrade 2>/dev/null; then
        sed -i '2i\# NAIXI_PROTECT\nif [ ! -f /tmp/naixi_upgrade_allow ]; then\n  echo "Naixi: 远程升级已阻止。本地升级请先运行: touch /tmp/naixi_upgrade_allow"\n  exit 1\nfi' /sbin/sysupgrade
    fi
    # Hook wecom.sh reboot/upgrade
    if ! grep -q "NAIXI_PROTECT" /usr/ikuai/script/wecom.sh 2>/dev/null; then
        sed -i '/^reboot()$/,/^}$/{/^reboot()/a\# NAIXI_PROTECT\nreturn 0
}' /usr/ikuai/script/wecom.sh
        sed -i '/^upgrade()$/,/^}$/{/^upgrade()/a\# NAIXI_PROTECT\nreturn 0
}' /usr/ikuai/script/wecom.sh
    fi
    echo "[Naixi] Level 0: 防格式化+防远程升级"
}

_apply_level1() {
    _apply_level0
    sed -i 's/59\.110\.6\.135/127.0.0.1/g' /usr/ikuai/script/client.sh 2>/dev/null
    mkdir -p /etc/hosts.d
    cat > /etc/hosts.d/naixi_block << 'HOSTS'
127.0.0.1 genuine.ikuai8.com
127.0.0.1 coll.ikuai8.com
127.0.0.1 iapi.ikuai8.com
127.0.0.1 audit.ikuai8.com
HOSTS
    cat /etc/hosts.d/* > /etc/hosts 2>/dev/null
    pkill -f "update_hosts.sh" 2>/dev/null
    rm -rf /tmp/iktmp/ik_hosts/* 2>/dev/null
    _iptables_block_collect
    echo "[Naixi] Level 1: 采集/验证阻断，云平台可用"
}

_apply_level2() {
    _apply_level1
    cat >> /etc/hosts.d/naixi_block << 'HOSTS'
127.0.0.1 dpi.ikuai8.com
127.0.0.1 download.ikuai8.com
127.0.0.1 www.ikuai8.com
127.0.0.1 local.ikuai8.com
127.0.0.1 portal.ikuai8.com
127.0.0.1 yun.ikuai8.com
127.0.0.1 302.ikuai8.com
127.0.0.1 youyu.api.ikuai8.com
127.0.0.1 routers.ikuai8.com
127.0.0.1 as1.ikuai8.com
127.0.0.1 as2.ikuai8.com
127.0.0.1 open.ikuai8.com
HOSTS
    cat /etc/hosts.d/* > /etc/hosts 2>/dev/null
    # Patch webman.lua: 阻止云绑定API代理
    local wlua="/usr/openresty/lua/lib/webman.lua"
    if [ -f "$wlua" ] && grep -q 'yun.ikuai8.com' "$wlua" 2>/dev/null; then
        sed -i 's|https://yun.ikuai8.com/api/v3/router_bind/|http://127.0.0.1/|g' "$wlua"
        /usr/sbin/openresty -s reload 2>/dev/null
        echo "[Naixi] webman.lua: 云绑定API已阻断"
    fi
    _iptables_block_ikuai_full
    # Patch monitor_process.sh: 禁止重启 ik_rc_client
    if [ -f /usr/ikuai/script/utils/monitor_process.sh ] && ! grep -q "NAIXI_BLOCK_RC" /usr/ikuai/script/utils/monitor_process.sh; then
        sed -i '/ik_rc_client/i\# NAIXI_BLOCK_RC\nreturn 0' /usr/ikuai/script/utils/monitor_process.sh 2>/dev/null
    fi
    pkill -9 ik_rc_client 2>/dev/null
    # 重命名二进制阻止 monitor 拉起
    [ -f /usr/sbin/ik_rc_client ] && mv /usr/sbin/ik_rc_client /usr/sbin/ik_rc_client.naixi_disabled
    pkill -9 dtalkd 2>/dev/null
    [ -f /usr/sbin/dtalkd ] && mv /usr/sbin/dtalkd /usr/sbin/dtalkd.naixi_disabled
    pkill -f "wecom.sh" 2>/dev/null
    pkill -f "DTalkInside" 2>/dev/null
    echo "[Naixi] Level 2: 全阻断+iptables"
}

do_ikuaiyun() {
    local level="$1"
    mkdir -p "$NAIXI_CONF"
    if [ -z "$level" ]; then
        local cur=$(cat "$NAIXI_CONF/ikuaiyun_level" 2>/dev/null || echo "2")
        echo "当前云平台控制等级: Level $cur"
        echo "  0 = 正常(仅防格式化/强制升级)"
        echo "  1 = 采集/验证阻断，云平台可用"
        echo "  2 = 全阻断(默认)"
        echo "  clean = 清除云平台绑定信息"
        return
    fi
    case "$level" in
        0) _apply_level0 ;; 1) _apply_level1 ;; 2) _apply_level2 ;;
        clean)
            sqlite3 /etc/mnt/ikuai/config.db "UPDATE register SET code='', node=0, comment='' WHERE id=1" 2>/dev/null
            rm -f /tmp/iktmp/register_status
            echo "✅ 云平台绑定信息已清除"
            return
            ;;
        *) echo "❌ 无效等级: $level (0/1/2/clean)"; exit 1 ;;
    esac
    echo "$level" > "$NAIXI_CONF/ikuaiyun_level"
    echo "✅ 云平台控制等级: Level $level"
}

do_boot_apply() {
    local level=$(cat "$NAIXI_CONF/ikuaiyun_level" 2>/dev/null || echo "2")
    case "$level" in
        0) _apply_level0 ;; 1) _apply_level1 ;; 2) _apply_level2 ;;
    esac
}



# ===== musl兼容层 (v59新增) =====
OWRT_ROOT="$NAIXI_DIR/openwrt-root"
_DL_BASE="https://dl.naixi.net/ikuai-plugin"

do_openwrt_init() {
    local force=0
    local arg=""
    for a in "$@"; do
        case "$a" in
            --force|-f) force=1 ;;
            *) arg="$a" ;;
        esac
    done
    if [ "$force" = 0 ] && [ -d "$OWRT_ROOT/bin" ] && [ -f "$NAIXI_DIR/opkg-root/www/cgi-bin/luci" ]; then
        echo "✅ 兼容层已完整 (musl=$(du -sh $OWRT_ROOT 2>/dev/null | cut -f1) + LuCI)"
        echo "   如需重装加 --force"
        return 0
    fi

    local combined_url=""
    case "$arg" in
        "")    combined_url="${_DL_BASE}/naixi-compat-x86_64.tar.gz" ;;
        http*) combined_url="$arg" ;;
        *)     echo "❌ 未知参数: $arg"; return 1 ;;
    esac

    echo "📦 下载 Naixi 兼容层..."
    echo "  $combined_url"
    if ! wget -q -O /tmp/naixi-compat.tar.gz "$combined_url"; then
        echo "❌ 下载失败"; return 1
    fi

    local stage=/tmp/naixi-compat-stage
    rm -rf "$stage" && mkdir -p "$stage"
    tar xzf /tmp/naixi-compat.tar.gz -C "$stage" 2>/dev/null || { echo "❌ 解压失败"; return 1; }

    echo "📦 安装 musl 兼容层..."
    if [ -d "$stage/openwrt-root" ]; then
        cp -a "$stage/openwrt-root" "$NAIXI_DIR/"
        ln -sf "$NAIXI_DIR/openwrt-root/lib/ld-musl-x86_64.so.1" /lib/ld-musl-x86_64.so.1 2>/dev/null
        echo "$NAIXI_DIR/opkg-root/usr/lib" > /etc/ld-musl-x86_64.path
        echo "$NAIXI_DIR/openwrt-root/lib" >> /etc/ld-musl-x86_64.path
        echo "$NAIXI_DIR/openwrt-root/usr/lib" >> /etc/ld-musl-x86_64.path
        echo "/usr/lib" >> /etc/ld-musl-x86_64.path
        echo "  ✅ musl → $NAIXI_DIR/openwrt-root"
    fi

    if [ -d "$stage/opkg" ]; then
        cp -a "$stage/opkg" "$NAIXI_DIR/"
        [ -f "$NAIXI_DIR/opkg/opkg" ] && cp "$NAIXI_DIR/opkg/opkg" /usr/bin/opkg && chmod +x /usr/bin/opkg
        [ -f "$NAIXI_DIR/opkg/opkg.real" ] && cp "$NAIXI_DIR/opkg/opkg.real" /usr/bin/opkg.real && chmod +x /usr/bin/opkg.real
        echo "  ✅ opkg → /usr/bin/opkg"
    fi

    echo "📦 安装 LuCI 兼容层..."
    if [ -d "$stage/opkg-root" ]; then
        mkdir -p "$NAIXI_DIR/opkg-root"
        cp -a "$stage/opkg-root/"* "$NAIXI_DIR/opkg-root/"
        rm -rf "$NAIXI_DIR/opkg-root/lib/modules/"
        echo "  ✅ LuCI → $NAIXI_DIR/opkg-root"
    fi

    echo "📦 创建启动脚本..."
    mkdir -p "$NAIXI_DIR/compat"
    if [ -f "$NAIXI_DIR/opkg-root/.compat/start.sh" ]; then
        cp "$NAIXI_DIR/opkg-root/.compat/start.sh" "$NAIXI_DIR/compat/start.sh"
        chmod +x "$NAIXI_DIR/compat/start.sh"
    fi
    cat > "$NAIXI_DIR/compat/boot.sh" << 'CBEOF'
#!/bin/bash
(
    for i in $(seq 1 60); do pidof openresty >/dev/null && break; sleep 2; done
    sleep 5
    bash /etc/log/naixi/compat/start.sh > /tmp/naixi_compat.log 2>&1
) &
CBEOF
    chmod +x "$NAIXI_DIR/compat/boot.sh"

    rm -rf "$stage" /tmp/naixi-compat.tar.gz

    if [ -f "$NAIXI_DIR/compat/start.sh" ]; then
        bash "$NAIXI_DIR/compat/start.sh"
        echo ""
        echo "🥛 LuCI: http://$(cat /proc/sys/kernel/hostname 2>/dev/null || echo iKuai):9090"
        echo "   密码与远程维护密码一致"
    fi
    echo "✅ 兼容层安装完成"
}


do_openwrt_clean() {
    local force=0
    [ "${1:-}" = "--force" ] || [ "${1:-}" = "-f" ] && force=1
    if [ "$force" = 1 ]; then
        echo "⚠️  --force 模式：会同时清理 host 侧 opkg 安装包（可能影响宎住系统运行）"
    else
        echo "清理 chroot 内的 opkg 包（host 侧保留，需同时清 host 加 --force）"
    fi
    if [ -d "$OWRT_ROOT/bin" ]; then
        _chroot_mount "$OWRT_ROOT"
        chroot "$OWRT_ROOT" /bin/opkg list-installed 2>/dev/null | awk '{print $1}' | while read pkg; do
            [ -z "$pkg" ] && continue
            chroot "$OWRT_ROOT" /bin/opkg --force-depends remove "$pkg" >/dev/null 2>&1 && echo "  - $pkg [musl]"
        done
        _chroot_umount "$OWRT_ROOT"
    fi
    if [ "$force" = 1 ] && which opkg >/dev/null 2>&1; then
        opkg list-installed 2>/dev/null | awk '{print $1}' | while read pkg; do
            [ "$pkg" = "opkg" ] && continue
            [ -z "$pkg" ] && continue
            opkg --force-depends remove "$pkg" >/dev/null 2>&1 && echo "  - $pkg [host]"
        done
        rm -f "$NAIXI_DIR/opkg-installed.txt"
    fi
    echo "✅ 完成"
}

do_openwrt_uninit() {
    local force=0
    [ "${1:-}" = "--force" ] || [ "${1:-}" = "-f" ] && force=1
    if [ ! -d "$OWRT_ROOT" ] && ! which opkg >/dev/null 2>&1; then
        echo "兼容层未安装"
        return 0
    fi
    if [ "$force" = 0 ]; then
        echo "⚠️  卸载会删除 musl chroot + opkg 二进制，but 保留 host 已装包 ($NAIXI_DIR/opkg-root)"
        echo "   如果要连 host 包一起干净卸载，请使用: naixi openwrt uninit --force"
        echo "   ⚠️  --force 可能删掉 ikuai/bash 正在使用的 lib，造成系统不可用"
    fi
    # 先 chroot clean（需要 force 才会连 host 包清）
    if [ "$force" = 1 ]; then
        do_openwrt_clean --force
    else
        do_openwrt_clean
    fi
    # 卸 musl chroot
    if [ -d "$OWRT_ROOT" ]; then
        _chroot_umount "$OWRT_ROOT"
        umount "$OWRT_ROOT/dev/pts" 2>/dev/null
        umount -l "$OWRT_ROOT/dev" 2>/dev/null
        umount -l "$OWRT_ROOT/tmp" 2>/dev/null
        umount -l "$OWRT_ROOT/proc" 2>/dev/null
        umount -l "$OWRT_ROOT/sys" 2>/dev/null
        rm -rf "$OWRT_ROOT"
    fi
    # 卸 opkg 本身
    rm -f /usr/bin/opkg /usr/bin/opkg.real /usr/sbin/opkg-check-config /usr/sbin/opkg-key /lib/functions.sh
    rm -rf /etc/opkg /etc/opkg.conf /var/lock/opkg.lock
    rm -rf /usr/lib/opkg/info /usr/lib/opkg/lists
    rm -f /lib/ld-musl-x86_64.so.1
    # ld-musl path 处理：重置到 /usr/lib 只让 host 原生生效
    echo /usr/lib > /etc/ld-musl-x86_64.path
    if [ "$force" = 1 ]; then
        rm -rf "$NAIXI_DIR/opkg-root"
        echo "✅ 兼容层已完全卸载（musl + opkg + 所有包）"
    else
        echo "✅ 兼容层已卸载。host 安装包保留于 $NAIXI_DIR/opkg-root"
    fi
}

_chroot_mount() {
    mount --bind /proc "$1/proc" 2>/dev/null
    mount --bind /sys "$1/sys" 2>/dev/null
    mount --bind /dev "$1/dev" 2>/dev/null
    mount --bind /tmp "$1/tmp" 2>/dev/null
    cp /etc/resolv.conf "$1/etc/resolv.conf" 2>/dev/null
}
_chroot_umount() {
    umount "$1/tmp" "$1/dev" "$1/sys" "$1/proc" 2>/dev/null
}

do_openwrt_shell() {
    [ ! -d "$OWRT_ROOT/bin" ] && { echo "请先运行: naixi openwrt init (初始化musl兼容层)"; return 1; }
    _chroot_mount "$OWRT_ROOT"
    chroot "$OWRT_ROOT" /bin/ash
    _chroot_umount "$OWRT_ROOT"
}

do_opkg() {
    local action="$1"
    shift
    if ! which opkg >/dev/null 2>&1; then
        echo "❌ opkg未安装，请先: naixi install opkg.tar.gz"
        return 1
    fi
    case "$action" in
        install)
            echo "安装: $@"
            mkdir -p "$NAIXI_DIR/opkg-root"
            grep -q "dest naixi" /etc/opkg.conf 2>/dev/null || echo "dest naixi $NAIXI_DIR/opkg-root" >> /etc/opkg.conf
            opkg install --force-depends --force-space --force-checksum -d naixi "$@" 2>/dev/null || opkg install --force-depends --force-space --force-checksum "$@"
            # 保存已装列表用于重启恢复
            opkg list-installed > "$NAIXI_DIR/opkg-installed.txt" 2>/dev/null
            echo "✅ 完成"
            ;;
        update|list|search|info|remove|upgrade)
            opkg "$action" "$@"
            ;;
        *)
            echo "用法: naixi opkg <install|update|list|search|info|remove> [参数]"
            ;;
    esac
}

do_ipk() {
    local ipk="$1"
    [ -z "$ipk" ] && echo "用法: naixi ipk <file.ipk|url>" && return 1
    local tmpipk="/tmp/naixi_ipk.ipk"
    if echo "$ipk" | grep -q "^http"; then
        wget -q -O "$tmpipk" "$ipk" || { echo "❌ 下载失败"; return 1; }
    elif [ -f "$ipk" ]; then cp "$ipk" "$tmpipk"
    else echo "❌ 文件不存在: $ipk"; return 1; fi

    # 检测musl
    local is_musl=0
    local tmpdir="/tmp/naixi_ipk_chk"
    mkdir -p "$tmpdir" && cd "$tmpdir"
    ar x "$tmpipk" 2>/dev/null
    [ -f data.tar.gz ] && tar xzf data.tar.gz 2>/dev/null
    local bin=$(find . -type f -executable 2>/dev/null | head -1)
    [ -n "$bin" ] && strings "$bin" 2>/dev/null | grep -q "musl" && is_musl=1
    cd /tmp && rm -rf "$tmpdir"

    if [ "$is_musl" -eq 1 ]; then
        echo "musl libc → 安装到chroot"
        [ ! -d "$OWRT_ROOT/bin" ] && do_openwrt_init
        cp "$tmpipk" "$OWRT_ROOT/tmp/"
        _chroot_mount "$OWRT_ROOT"
        chroot "$OWRT_ROOT" /bin/opkg install "/tmp/$(basename $tmpipk)"
        _chroot_umount "$OWRT_ROOT"
    else
        echo "原生兼容 → 手动解压安装"
        local tmpdir2="/tmp/naixi_ipk_inst"
        mkdir -p "$tmpdir2" && cd "$tmpdir2"
        ar x "$tmpipk" 2>/dev/null
        [ -f data.tar.gz ] && tar xzf data.tar.gz -C / 2>/dev/null
        cd /tmp && rm -rf "$tmpdir2"
    fi
    rm -f "$tmpipk"
    echo "✅ 安装完成"
}
case "${1:-}" in
    list)      do_list ;;
    install)   do_install "$2" ;;
    enable)    do_enable "$2" ;;
    disable)   do_disable "$2" ;;
    remove)    do_remove "$2" ;;
    status)    do_status "$2" ;;
    ipv6)      do_ipv6 "$2" ;;
    ikuaiyun)  do_ikuaiyun "$2" ;;
    _boot)     do_boot_apply ;;
    openwrt)
        case "${2:-}" in
            init) shift 2; do_openwrt_init "$@" ;;
            uninit) do_openwrt_uninit "${3:-}" ;;
            clean) do_openwrt_clean "${3:-}" ;;
            shell) do_openwrt_shell ;;
            *) echo "用法: naixi openwrt init [<url>] [--force]|shell|clean [--force]|uninit [--force]" ;;
        esac ;;
    opkg) shift; do_opkg "$@" ;;
    ipk) do_ipk "$2" ;;
    *)         usage ;;
esac
