#!/bin/sh
# GL-iNet MT-2500A/MT-3000/MT-6000 一键iStoreOS风格化脚本
# by @wukongdaily

HTTP_HOST="https://cafe.cpolar.cn/wkdaily/gl/raw/branch/main"
LIB_COMMON="/tmp/lib-common.sh"

# 设置全局命令 g
cp -f "$0" /usr/bin/g
chmod +x /usr/bin/g

# 下载并加载公共库
load_common_lib() {
    rm -f "$LIB_COMMON"
    wget -O "$LIB_COMMON" "$HTTP_HOST/lib/lib-common.sh" 2>/dev/null || {
        echo "下载公共库失败"
        exit 1
    }
    . "$LIB_COMMON"
}

# MT系列专用：架构配置
add_arch() {
    if ! wget -O /etc/opkg/arch.conf $HTTP_HOST/mtarch/arch.conf; then
        echo "下载 arch.conf 失败，脚本终止。"
        exit 1
    fi
}

# 安装应用商店和主题
install_istore_os_style() {
    do_install_argon_skin
    opkg install ttyd
    do_install_filetransfer
    is-opkg install app-meta-sftp
    is-opkg install 'app-meta-ddnsto'
    is-opkg install 'app-meta-diskman'
    FILE_PATH="/etc/openwrt_release"
    NEW_DESCRIPTION="Openwrt like iStoreOS Style by wukongdaily"
    CONTENT=$(cat $FILE_PATH)
    UPDATED_CONTENT=$(echo "$CONTENT" | sed "s/DISTRIB_DESCRIPTION='[^']*'/DISTRIB_DESCRIPTION='$NEW_DESCRIPTION'/")
    echo "$UPDATED_CONTENT" >$FILE_PATH
}

# 设置风扇工作温度
setup_cpu_fans() {
    uci set glfan.@globals[0].temperature=50
    uci set glfan.@globals[0].warn_temperature=50
    uci set glfan.@globals[0].integration=4
    uci set glfan.@globals[0].differential=20
    uci commit glfan
    /etc/init.d/gl_fan restart
}

# 添加自定义软件源
add_custom_feed() {
    echo "# add your custom package feeds here" >/etc/opkg/customfeeds.conf
    echo "请输入自定义软件源的地址(通常是https开头 aarch64_cortex-a53 结尾):"
    read feed_url
    if [ -n "$feed_url" ]; then
        echo "src/gz custom_feed $feed_url" >>/etc/opkg/customfeeds.conf
        opkg update
        if [ $? -eq 0 ]; then
            echo "已添加并更新列表."
        else
            echo "已添加但更新失败,请检查网络或重试."
        fi
    else
        echo "Error: Feed URL not provided."
    fi
}

# 删除自定义软件源
remove_custom_feed() {
    echo "# add your custom package feeds here" >/etc/opkg/customfeeds.conf
    opkg update
    if [ $? -eq 0 ]; then
        echo "已删除并更新列表."
    else
        echo "已删除了自定义软件源但更新失败,请检查网络或重试."
    fi
}

# 恢复原厂OPKG配置
recovery_opkg_settings() {
    echo "# add your custom package feeds here" >/etc/opkg/customfeeds.conf
    router_name=$(get_router_name)
    case "$router_name" in
    *3000*)
        mt3000_opkg="$HTTP_HOST/mt-3000/distfeeds.conf"
        wget -O /etc/opkg/distfeeds.conf ${mt3000_opkg}
        ;;
    *2500*)
        mt2500a_opkg="$HTTP_HOST/mt-2500a/distfeeds.conf"
        wget -O /etc/opkg/distfeeds.conf ${mt2500a_opkg}
        ;;
    *6000*)
        update_opkg_config
        ;;
    *)
        echo "Router name does not contain '3000', '6000' or '2500'."
        ;;
    esac
}

# MT6000专用：更新OPKG配置
update_opkg_config() {
    kernel_version=$(uname -r)
    echo "MT-6000 kernel version: $kernel_version"
    case $kernel_version in
    5.4*)
        mt6000_opkg="$HTTP_HOST/mt-6000/distfeeds-5.4.conf"
        wget -O /etc/opkg/distfeeds.conf ${mt6000_opkg}
        mkdir -p /tmp/mt6000
        wget --user-agent="Mozilla/5.0" -O /tmp/mt6000/script-utils.ipk "$HTTP_HOST/mt-6000/script-utils.ipk"
        wget --user-agent="Mozilla/5.0" -O /tmp/mt6000/mdadm.ipk "$HTTP_HOST/mt-6000/mdadm.ipk"
        wget --user-agent="Mozilla/5.0" -O /tmp/mt6000/lsblk.ipk "$HTTP_HOST/mt-6000/lsblk.ipk"
        opkg update
        if [ -f "/tmp/mt6000/lsblk.ipk" ]; then
            opkg remove lsblk
        fi
        opkg install /tmp/mt6000/*.ipk
        ;;
    5.15*)
        mt6000_opkg="$HTTP_HOST/mt-6000/distfeeds.conf"
        wget -O /etc/opkg/distfeeds.conf ${mt6000_opkg}
        ;;
    *)
        echo "Unsupported kernel version: $kernel_version"
        return 1
        ;;
    esac
}

# 更新首页风格
update_luci_app_quickstart() {
    if [ -f "/bin/is-opkg" ]; then
        is-opkg update
        is-opkg install luci-i18n-quickstart-zh-cn --force-depends >/dev/null 2>&1
        opkg install iptables-mod-tproxy
        opkg install iptables-mod-socket
        opkg install iptables-mod-iprange
        do_install_new_quickstart
        yellow "恭喜您!现在你的路由器已经变成iStoreOS风格啦!"
        green "现在您可以访问8080端口 查看是否生效 http://192.168.8.1:8080"
        green "更多up主项目和动态 请务必收藏我的导航站 https://tvhelper.cpolar.cn"
    else
        red "请先执行第一项 一键iStoreOS风格化"
    fi
}

# 安装文件管理器
do_install_filemanager() {
    echo "为避免bug,安装文件管理器之前,需要先iStore商店"
    do_istore_generic
    echo "接下来尝试安装文件管理器..."
    is-opkg install 'app-meta-linkease'
    echo "重新登录web页面,然后您可以访问: http://192.168.8.1/cgi-bin/luci/admin/services/linkease/file/?path=/root"
}

# 更新脚本
update_myself() {
    wget -O gl-inet.sh "$HTTP_HOST/gl-inet.sh" && chmod +x gl-inet.sh
    echo "脚本已更新并保存在当前目录 gl-inet.sh,现在将执行新脚本。"
    ./gl-inet.sh
    exit 0
}

# MT3000更换分区
mt3000_overlay_changed() {
    wget -O mt3000.sh "$HTTP_HOST/mt-3000/mt3000.sh" && chmod +x mt3000.sh
    sh mt3000.sh
}

# ============================================================================
# 一键执行函数
# ============================================================================
run_quick_install() {
    sh /usr/bin/init_luci.sh web
    add_arch
    if [[ "$gl_name" == *3000* ]]; then
        setup_cpu_fans
    fi
    recovery_opkg_settings
    do_istore_generic
    install_istore_os_style
    update_luci_app_quickstart
    setup_base_init
    do_install_ui_helper
    show_completion_message
}

# ============================================================================
# 主程序
# ============================================================================
load_common_lib

# 检查是否传入 --quick 参数
if [ "$1" = "--quick" ] || [ "$1" = "-q" ]; then
    run_quick_install
    exit 0
fi

while true; do
    clear
    gl_name=$(get_router_name)
    result=$gl_name"一键iStoreOS风格化(新版)"
    result=$(echo "$result" | sed 's/ like iStoreOS//')
    echo "***********************************************************************"
    echo "*      一键安装工具箱(for gl-inet Router)"
    echo "*      by @wukongdaily"
    echo "**********************************************************************"
    echo "*      当前的路由器型号: $gl_name" | sed 's/ like iStoreOS//'
    echo
    echo "*******支持的机型列表***************************************************"
    green "*******GL-iNet MT-2500A"
    green "*******GL-iNet MT-3000"
    green "*******GL-iNet MT-6000"
    echo "******************下次调用 直接输入快捷键 g  *****************************"
    echo
    light_magenta " 1. $result"
    echo
    echo " 2. 设置自定义软件源"
    echo " 3. 删除自定义软件源"
    echo
    echo " 4. 设置风扇开始工作的温度(仅限MT3000)"
    echo " 5. 恢复原厂OPKG配置软件包"
    echo
    echo " 6. 更新luci-app-quickstart"
    echo " 7. 安装Argon紫色主题"
    echo " 8. 安装文件管理器"
    light_magenta " 9. MT3000一键更换分区"
    light_magenta "10. 隐藏首页非必要UI元素"
    light_magenta "11. 安装个性化UI辅助插件(by VMatrices)"
    light_magenta "12. 更新脚本"
    echo
    echo " Q. 退出本程序"
    echo
    read -p "请选择一个选项: " choice

    case $choice in
    1)
        run_quick_install
        ;;
    2)
        add_custom_feed
        ;;
    3)
        remove_custom_feed
        ;;
    4)
        case "$gl_name" in
        *3000*)
            set_glfan_temp
            ;;
        *)
            echo "当前的路由器型号: $gl_name" | sed 's/ like iStoreOS//'
            echo "并非MT3000 它没有风扇 无需设置"
            ;;
        esac
        ;;
    5)
        recovery_opkg_settings
        ;;
    6)
        update_luci_app_quickstart
        ;;
    7)
        do_install_argon_skin
        ;;
    8)
        do_install_filemanager
        ;;
    9)
        mt3000_overlay_changed
        ;;
    10)
        hide_ui_elements
        ;;
    11)
        do_install_ui_helper
        ;;
    12)
        update_myself
        ;;
    q | Q)
        echo "退出"
        exit 0
        ;;
    *)
        echo "无效选项，请重新选择。"
        ;;
    esac

    read -p "按 Enter 键继续..."
done