#!/bin/bash
# Naixi 系统管理器 v4.0
# 用法: naixi <命令> [参数]
NAIXI_DIR="/etc/log/naixi"
IKPKG_DIR="/tmp/ikpkg"
NAIXI_CONF="$NAIXI_DIR/.config"
OWRT_ROOT="$NAIXI_DIR/openwrt-root"
DL_BASE="https://dl.naixi.net/ikuai-plugin"
mkdir -p "$NAIXI_DIR"

usage() {
    cat << 'EOF'
Naixi 系统管理器 v4.0

插件管理:
  naixi list                 列出所有插件
  naixi install <url|path>   安装插件(tar.gz)
  naixi enable <name>        启用插件
  naixi disable <name>       禁用插件
  naixi remove <name>        卸载并删除插件
  naixi status <name>        查看插件状态

系统:
  naixi ipv6 [num]           查看/设置IPv6多线数量
  naixi ikuaiyun [0|1|2]     云平台控制等级
  naixi ssh [on|off]         SSH开关
  naixi passwd <pw>          修改SSH密码
  naixi diag                 系统诊断

OpenWrt扩展:
  naixi openwrt init         下载并初始化chroot环境
  naixi openwrt shell        进入chroot shell
  naixi opkg <参数>          在chroot中运行opkg
  naixi ipk <file|url>       安装ipk包(自动识别musl/原生)
EOF
}

# ===== 插件管理 (v57原有功能) =====

do_list() {
    echo "=== Naixi 插件 ==="
    local found=0
    for dir in $NAIXI_DIR/*/; do
        [ -d "$dir" ] || continue
        name=$(basename "$dir")
        [ "$name" = "lost+found" -o "$name" = ".config" -o "$name" = "openwrt-root" ] && continue
        found=1
        if [ -f "$dir/.disabled" ]; then echo "  ✗ $name (已禁用)"
        elif [ -d "$IKPKG_DIR/$name" ]; then echo "  ✓ $name (运行中)"
        else echo "  - $name (未加载)"; fi
    done
    [ $found -eq 0 ] && echo "  (无插件)"
    echo ""
    local level=$(cat "$NAIXI_CONF/ikuaiyun_level" 2>/dev/null || echo "1")
    echo "云平台控制: Level $level"
    [ -d "$OWRT_ROOT/bin" ] && echo "OpenWrt chroot: ✓ 已初始化" || echo "OpenWrt chroot: ✗ 未初始化"
}

do_install() {
    local src="$1"
    [ -z "$src" ] && echo "用法: naixi install <url|path>" && return 1
    local fname=$(basename "$src")
    local name="${fname%.tar.gz}"
    if echo "$src" | grep -qE "^https?://"; then
        echo "下载: $src"
        wget -q -O "$NAIXI_DIR/$fname" "$src" || { echo "❌ 下载失败"; return 1; }
    elif [ -f "$src" ]; then
        echo "复制: $src"
        cp "$src" "$NAIXI_DIR/$fname"
    else
        echo "❌ 文件不存在: $src"; return 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>" && return 1
    local dir="$NAIXI_DIR/$name"
    [ ! -d "$dir" ] && echo "❌ 插件不存在: $name" && return 1
    [ ! -f "$dir/install.sh" ] && echo "❌ 缺少install.sh: $name" && return 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
    echo "✅ $name 已启用"
}

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

do_status() {
    local name="$1"
    [ -z "$name" ] && echo "用法: naixi status <name>" && return 1
    local dir="$NAIXI_DIR/$name"
    [ ! -d "$dir" ] && echo "❌ 插件不存在: $name" && return 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"
}

do_ssh() {
    case "${1:-}" in
        on)  /usr/sbin/dropbear -p 22 2>/dev/null; echo "✅ SSH已开启 (端口22)" ;;
        off) killall dropbear 2>/dev/null; echo "✅ SSH已关闭" ;;
        *)   netstat -tlnp 2>/dev/null | grep -q ':22 ' && echo "SSH: 运行中" || echo "SSH: 已停止"
             echo "  naixi ssh on|off" ;;
    esac
}

do_passwd() {
    local pw="$1"
    [ -z "$pw" ] && echo "用法: naixi passwd <密码>" && return 1
    echo "root:${pw}" | chpasswd 2>/dev/null
    echo "sshd:${pw}" | chpasswd 2>/dev/null
    echo "✅ root和sshd密码已更新"
}

do_diag() {
    echo "=== Naixi 系统诊断 ==="
    echo ""
    echo "网络:"
    ping -c1 -W2 8.8.8.8 >/dev/null 2>&1 && echo "  互联网: ✅" || echo "  互联网: ❌"
    ping -c1 -W2 dl.naixi.net >/dev/null 2>&1 && echo "  dl.naixi.net: ✅" || echo "  dl.naixi.net: ❌"
    echo ""
    echo "磁盘:"
    df -h /etc/log 2>/dev/null | awk 'NR==2{printf "  /etc/log: %s/%s (%s 已用)\n", $3, $2, $5}'
    echo ""
    echo "进程:"
    for p in pmd ik_core httpd dropbear dockerd; do
        pidof $p >/dev/null 2>&1 && echo "  $p: ✅ 运行中" || echo "  $p: ❌ 已停止"
    done
    echo ""
    echo "云控:"
    local level=$(cat "$NAIXI_CONF/ikuaiyun_level" 2>/dev/null || echo "1")
    echo "  等级: Level $level"
}

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

_apply_level0() {
    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: 远程升级已阻止"\n  exit 1\nfi' /sbin/sysupgrade
    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 yun.ikuai8.com
127.0.0.1 302.ikuai8.com
127.0.0.1 youyu.api.ikuai8.com
127.0.0.1 audit.ikuai8.com
127.0.0.1 routers.ikuai8.com
HOSTS
    cat /etc/hosts.d/* > /etc/hosts 2>/dev/null
    pkill -f "update_hosts.sh" 2>/dev/null
    echo "[Naixi] Level 1: 云控阻断，DPI保留"
}

_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
HOSTS
    cat /etc/hosts.d/* > /etc/hosts 2>/dev/null
    echo "[Naixi] Level 2: 全阻断"
}

do_ikuaiyun() {
    local level="$1"
    mkdir -p "$NAIXI_CONF"
    if [ -z "$level" ]; then
        local cur=$(cat "$NAIXI_CONF/ikuaiyun_level" 2>/dev/null || echo "1")
        echo "当前云平台控制等级: Level $cur"
        echo "  0 = 正常(仅防格式化/强制升级)"
        echo "  1 = 阻断云控/验证，保留DPI(默认)"
        echo "  2 = 彻底阻断所有ikuai8.com"
        return
    fi
    case "$level" in
        0) _apply_level0 ;; 1) _apply_level1 ;; 2) _apply_level2 ;;
        *) echo "❌ 无效等级: $level (0/1/2)"; return 1 ;;
    esac
    echo "$level" > "$NAIXI_CONF/ikuaiyun_level"
    echo "✅ 云平台控制等级: Level $level"
}

# ===== OpenWrt chroot =====

do_openwrt_init() {
    if [ -d "$OWRT_ROOT/bin" ]; then
        echo "OpenWrt chroot 已初始化 ($(du -sh $OWRT_ROOT | cut -f1))"
        return 0
    fi
    echo "下载 OpenWrt rootfs..."
    mkdir -p "$OWRT_ROOT"
    wget -q -O /tmp/openwrt-root.tar.gz "${DL_BASE}/openwrt-root-x86_64.tar.gz" || { echo "❌ 下载失败"; return 1; }
    tar xzf /tmp/openwrt-root.tar.gz -C "$OWRT_ROOT" && rm /tmp/openwrt-root.tar.gz
    echo "nameserver 8.8.8.8" > "$OWRT_ROOT/etc/resolv.conf"
    echo "✅ OpenWrt chroot 初始化完成 ($(du -sh $OWRT_ROOT | cut -f1))"
}

_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" 2>/dev/null
    umount "$1/dev" 2>/dev/null
    umount "$1/sys" 2>/dev/null
    umount "$1/proc" 2>/dev/null
}

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

do_opkg() {
    [ ! -d "$OWRT_ROOT/bin" ] && do_openwrt_init
    _chroot_mount "$OWRT_ROOT"
    chroot "$OWRT_ROOT" /bin/opkg "$@"
    _chroot_umount "$OWRT_ROOT"
}

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_check"
    mkdir -p "$tmpdir" && cd "$tmpdir"
    ar x "$tmpipk" 2>/dev/null
    if [ -f data.tar.gz ]; then tar xzf data.tar.gz 2>/dev/null; fi
    if [ -f data.tar.zst ]; then zstd -d data.tar.zst -o data.tar 2>/dev/null && tar xf data.tar 2>/dev/null; fi
    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"
        echo "✅ 已安装到 chroot"
    else
        echo "检测到原生兼容 → 直接安装"
        local tmpdir2="/tmp/naixi_ipk_inst"
        mkdir -p "$tmpdir2" && cd "$tmpdir2"
        ar x "$tmpipk" 2>/dev/null
        if [ -f data.tar.gz ]; then tar xzf data.tar.gz -C / 2>/dev/null; fi
        if [ -f data.tar.zst ]; then zstd -d data.tar.zst -o data.tar 2>/dev/null && tar xf data.tar -C / 2>/dev/null; fi
        cd /tmp && rm -rf "$tmpdir2"
        echo "✅ 已原生安装"
    fi
    rm -f "$tmpipk"
}

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

# ===== 主入口 =====

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" ;;
    ssh)       do_ssh "$2" ;;
    passwd)    do_passwd "$2" ;;
    diag)      do_diag ;;
    openwrt)
        case "${2:-}" in
            init)  do_openwrt_init ;;
            shell) do_openwrt_shell ;;
            *) echo "用法: naixi openwrt init|shell" ;;
        esac ;;
    opkg)      shift; do_opkg "$@" ;;
    ipk)       do_ipk "$2" ;;
    _boot)     do_boot_apply ;;
    help|--help|-h|"") usage ;;
    *)         echo "❌ 未知命令: $1"; usage ;;
esac
