#!/bin/sh
# GL-iNet 路由器工具箱公共函数库
# by @wukongdaily

# ============================================================================
# 颜色输出函数
# ============================================================================
red() { printf "\033[31m\033[01m%s\033[0m\n" "$1"; }
green() { printf "\033[32m\033[01m%s\033[0m\n" "$1"; }
yellow() { printf "\033[33m\033[01m%s\033[0m\n" "$1"; }
blue() { printf "\033[34m\033[01m%s\033[0m\n" "$1"; }
light_magenta() { printf "\033[95m\033[01m%s\033[0m\n" "$1"; }
light_yellow() { printf "\033[93m\033[01m%s\033[0m\n" "$1"; }
cyan() { printf "\033[38;2;0;255;255m%s\033[0m\n" "$1"; }

# ============================================================================
# 全局变量
# ============================================================================
HTTP_HOST="https://cafe.cpolar.cn/wkdaily/gl/raw/branch/main"
third_party_source="https://istore.linkease.com/repo/all/nas_luci"

# ============================================================================
# 路由器信息获取
# ============================================================================
get_router_name() {
    model_info=$(cat /tmp/sysinfo/model)
    echo "$model_info"
}

get_router_hostname() {
    hostname=$(uci get system.@system[0].hostname)
    echo "$hostname 路由器"
}

# ============================================================================
# 系统判断
# ============================================================================
is_iStoreOS() {
    DISTRIB_ID=$(cat /etc/openwrt_release | grep "DISTRIB_ID" | cut -d "'" -f 2)
    if [ "$DISTRIB_ID" = "iStoreOS" ]; then
        return 0
    else
        return 1
    fi
}

# ============================================================================
# OPKG 签名管理
# ============================================================================
remove_check_signature_option() {
    local opkg_conf="/etc/opkg.conf"
    sed -i '/option check_signature/d' "$opkg_conf"
}

add_check_signature_option() {
    local opkg_conf="/etc/opkg.conf"
    echo "option check_signature 1" >>"$opkg_conf"
}

# ============================================================================
# 软件源设置
# ============================================================================
setup_software_source() {
    if [ "$1" -eq 0 ]; then
        echo "# add your custom package feeds here" >/etc/opkg/customfeeds.conf
        if is_iStoreOS; then
            add_check_signature_option
        fi
        opkg update
        elif [ "$1" -eq 1 ]; then
        remove_check_signature_option
        echo "# add your custom package feeds here" >/etc/opkg/customfeeds.conf
        echo "src/gz third_party_source $third_party_source" >>/etc/opkg/customfeeds.conf
        opkg update
    else
        echo "Invalid option. Please provide 0 or 1."
    fi
}

# ============================================================================
# DHCP 域名映射 (解决安卓原生TV首次连不上wifi的问题)
# ============================================================================
add_dhcp_domain() {
    local domain_name="time.android.com"
    local domain_ip="203.107.6.88"
    
    existing_records=$(uci show dhcp | grep "dhcp.@domain\[[0-9]\+\].name='$domain_name'")
    if [ -z "$existing_records" ]; then
        uci add dhcp domain
        uci set "dhcp.@domain[-1].name=$domain_name"
        uci set "dhcp.@domain[-1].ip=$domain_ip"
        uci commit dhcp
    fi
}

# ============================================================================
# 作者信息添加
# ============================================================================
add_author_info() {
    uci set system.@system[0].description='wukongdaily'
    uci set system.@system[0].notes='文档说明:
    https://tvhelper.cpolar.cn/'
    uci commit system

    sed -i "s/boardinfo.kernel,_('Local Time')/boardinfo.kernel,'脚本美化','wukongdaily',_('Local Time')/" /www/luci-static/resources/view/status/include/10_system.js
    rm -rf /tmp/luci-*
    /etc/init.d/uhttpd restart
}

# ============================================================================
# 基础初始化
# ============================================================================
setup_base_init() {
    add_author_info
    add_dhcp_domain
    uci set system.@system[0].zonename='Asia/Shanghai'
    uci set system.@system[0].timezone='CST-8'
    uci commit system
    /etc/init.d/system reload
}

show_completion_message() {
    green "安装完毕！请使用8080端口访问luci界面：http://192.168.8.1:8080"
    green "作者更多动态务必收藏：https://tvhelper.cpolar.cn/"
}

# ============================================================================
# 隐藏首页无用元素
# ============================================================================
hide_ui_elements() {
    TARGET="/www/luci-static/quickstart/style.css"
    MARKER="/* hide custom luci elements */"
    
    if ! grep -q "$MARKER" "$TARGET"; then
        cat <<EOF >>"$TARGET"

$MARKER
/* 隐藏首页格式化按钮 */
.value-data button {
  display: none !important;
}

/* 隐藏网络页的第 3 个 item */
#main > div > div.network-container.align-c > div > div > div:nth-child(3) {
  display: none !important;
}

/* 隐藏网络页的第 5 个 item */
#main > div > div.network-container.align-c > div > div > div:nth-child(5) {
  display: none !important;
}

/* 隐藏 feature-card.pink */
#main > div > div.card-container > div.feature-card.pink {
  display: none !important;
}

EOF
        echo "✅ 自定义元素已隐藏"
    else
        echo "⚠️ 无需重复操作"
    fi
}

# ============================================================================
# 文件传输插件安装
# ============================================================================
do_install_filetransfer() {
    mkdir -p /tmp/luci-app-filetransfer/
    cd /tmp/luci-app-filetransfer/
    wget --user-agent="Mozilla/5.0" -O luci-app-filetransfer_all.ipk "$HTTP_HOST/luci-app-filetransfer/luci-app-filetransfer_all.ipk"
    wget --user-agent="Mozilla/5.0" -O luci-lib-fs_1.0-14_all.ipk "$HTTP_HOST/luci-app-filetransfer/luci-lib-fs_1.0-14_all.ipk"
    opkg install *.ipk --force-depends
}

# ============================================================================
# Argon 主题依赖安装
# ============================================================================
do_install_depends_ipk() {
    wget --user-agent="Mozilla/5.0" -O "/tmp/luci-lua-runtime_all.ipk" "$HTTP_HOST/theme/luci-lua-runtime_all.ipk"
    wget --user-agent="Mozilla/5.0" -O "/tmp/libopenssl3.ipk" "$HTTP_HOST/theme/libopenssl3.ipk"
    opkg install "/tmp/luci-lua-runtime_all.ipk"
    opkg install "/tmp/libopenssl3.ipk"
}

# ============================================================================
# Argon 主题安装
# ============================================================================
do_install_argon_skin() {
    echo "正在尝试安装argon主题..."
    do_install_depends_ipk
    opkg update
    opkg install luci-lib-ipkg
    wget --user-agent="Mozilla/5.0" -O "/tmp/luci-theme-argon.ipk" "$HTTP_HOST/theme/luci-theme-argon-master_2.2.9.4_all.ipk"
    wget --user-agent="Mozilla/5.0" -O "/tmp/luci-app-argon-config.ipk" "$HTTP_HOST/theme/luci-app-argon-config_0.9_all.ipk"
    wget --user-agent="Mozilla/5.0" -O "/tmp/luci-i18n-argon-config-zh-cn.ipk" "$HTTP_HOST/theme/luci-i18n-argon-config-zh-cn.ipk"
    cd /tmp/
    opkg install luci-theme-argon.ipk luci-app-argon-config.ipk luci-i18n-argon-config-zh-cn.ipk
    if [ $? -eq 0 ]; then
        echo "argon主题 安装成功"
        uci set luci.main.mediaurlbase='/luci-static/argon'
        uci set luci.main.lang='zh_cn'
        uci commit
        sed -i 's/value="<%:Login%>"/value="登录"/' /usr/lib/lua/luci/view/themes/argon/sysauth.htm
        echo "重新登录web页面后, 查看新主题"
    else
        echo "argon主题 安装失败! 建议再执行一次!"
    fi
}

# ============================================================================
# iStore 商店安装 (64位)
# ============================================================================
do_istore() {
    echo "do_istore 64bit ==================>"
    opkg update
    URL="https://repo.istoreos.com/repo/all/store/"
    DIR="/tmp/ipk_store"
    mkdir -p "$DIR"
    cd "$DIR" || exit 1
    
    for ipk in $(wget -qO- "$URL" | grep -oE 'href="[^"]+\.ipk"' | cut -d'"' -f2); do
        echo "下载 $ipk"
        wget -q "${URL}${ipk}"
    done
    
    opkg install ./*.ipk
}

# ============================================================================
# iStore 商店安装 (通用方法)
# ============================================================================
do_istore_generic() {
    echo "do_istore method==================>"
    ISTORE_REPO=https://istore.linkease.com/repo/all/store
    FCURL="curl --fail --show-error"
    
    curl -V >/dev/null 2>&1 || {
        echo "prereq: install curl"
        opkg info curl | grep -Fqm1 curl || opkg update
        opkg install curl
    }
    
    IPK=$($FCURL "$ISTORE_REPO/Packages.gz" | zcat | grep -m1 '^Filename: luci-app-store.*\.ipk$' | sed -n -e 's/^Filename: \(.\+\)$/\1/p')
    
    [ -n "$IPK" ] || exit 1
    
    $FCURL "$ISTORE_REPO/$IPK" | tar -xzO ./data.tar.gz | tar -xzO ./bin/is-opkg >/tmp/is-opkg
    
    [ -s "/tmp/is-opkg" ] || exit 1
    
    chmod 755 /tmp/is-opkg
    /tmp/is-opkg update
    /tmp/is-opkg opkg install --force-reinstall luci-lib-taskd luci-lib-xterm
    /tmp/is-opkg opkg install --force-reinstall luci-app-store || exit $?
    [ -s "/etc/init.d/tasks" ] || /tmp/is-opkg opkg install --force-reinstall taskd
    [ -s "/usr/lib/lua/luci/cbi.lua" ] || /tmp/is-opkg opkg install luci-compat >/dev/null 2>&1
}

# ============================================================================
# Quickstart 下载
# ============================================================================
download_luci_quickstart() {
    REPO_URL="https://repo.istoreos.com/repo/all/nas_luci/"
    DOWNLOAD_DIR="/tmp/ipk_downloads"
    mkdir -p "$DOWNLOAD_DIR"
    
    wget -qO- "$REPO_URL" | grep -oE 'href="[^"]*quickstart[^"]*\.ipk"' |
    sed 's/href="//;s/"//' | while read -r FILE; do
        echo "📦 正在下载: $FILE"
        wget -q -P "$DOWNLOAD_DIR" "$REPO_URL$FILE"
    done
    
    echo "✅ 所有 quickstart 相关 IPK 文件已下载到: $DOWNLOAD_DIR"
}

download_lib_quickstart() {
    REPO_URL="https://repo.istoreos.com/repo/aarch64_cortex-a53/nas/"
    DOWNLOAD_DIR="/tmp/ipk_downloads"
    mkdir -p "$DOWNLOAD_DIR"
    
    wget -qO- "$REPO_URL" | grep -oE 'href="[^"]*quickstart[^"]*\.ipk"' |
    sed 's/href="//;s/"//' | while read -r FILE; do
        echo "📦 正在下载: $FILE"
        wget -q -P "$DOWNLOAD_DIR" "$REPO_URL$FILE"
    done
    
    echo "✅ 所有 quickstart 相关 IPK 文件已下载到: $DOWNLOAD_DIR"
}

# ============================================================================
# 新首页风格安装 目前仓库内已经是最新quickstart了，无需更新安装
# ============================================================================
do_install_new_quickstart() {
    hide_ui_elements
    green "首页风格安装完毕！请使用8080端口访问luci界面：http://192.168.8.1:8080"
    green "作者更多动态务必收藏：https://tvhelper.cpolar.cn/"
}

# ============================================================================
# UI 辅助插件安装
# ============================================================================
do_install_ui_helper() {
    local ipk_file="/tmp/glinjector_3.0.5-6_all.ipk"
    local sha_file="${ipk_file}.sha256"
    
    echo "📥 正在下载 UI辅助插件..."
    wget -O "$sha_file" "$HTTP_HOST/ui/glinjector_3.0.5-6_all.ipk.sha256" || {
        echo "❌ 下载 SHA256 文件失败"
        return 1
    }
    
    wget --user-agent="Mozilla/5.0" -O "$ipk_file" "$HTTP_HOST/ui/glinjector_3.0.5-6_all.ipk" || {
        echo "❌ 下载 IPK 文件失败"
        return 1
    }
    
    echo "🔐 正在进行 SHA256 校验..."
    
    cd "$(dirname "$ipk_file")"
    sha256sum -c "$sha_file" || {
        echo "❌ 校验失败：文件已损坏或未完整下载"
        rm -f "$ipk_file"
        return 1
    }
    
    echo "✅ 校验通过，开始安装..."
    
    opkg update
    opkg install "$ipk_file"
}

# ============================================================================
# 恢复出厂设置
# ============================================================================
recovery() {
    echo "⚠️ 警告：此操作将恢复出厂设置，所有配置将被清除！"
    echo "⚠️ 请确保已备份必要数据。"
    read -p "是否确定执行恢复出厂设置？(yes/[no]): " confirm
    
    if [ "$confirm" = "yes" ]; then
        echo "正在执行恢复出厂设置..."
        firstboot -y >/dev/null 2>&1
        echo "操作完成，正在重启设备..."
        reboot
    else
        echo "操作已取消。"
    fi
}

# ============================================================================
# 风扇温度设置
# ============================================================================
set_glfan_temp() {
    echo "兼容带风扇机型的GL-iNet路由器"
    echo "请输入风扇开始工作的温度(建议40-70之间的整数):"
    read temp
    
    if [[ $temp =~ ^[0-9]+$ ]]; then
        uci set glfan.@globals[0].temperature="$temp"
        uci set glfan.@globals[0].warn_temperature="$temp"
        uci set glfan.@globals[0].integration=4
        uci set glfan.@globals[0].differential=20
        uci commit glfan
        /etc/init.d/gl_fan restart
        echo "设置成功！稍等片刻,请查看风扇转动情况"
    else
        echo "错误: 请输入整数."
    fi
}

