#!/bin/sh
# NX30Pro 一键升级脚本（路由器本地运行）
# 用法: wget -O- https://git.stickrouter.com/mike/N30pro/raw/branch/main/nx30pro_upgrade.sh | sh

FIRMWARE_URL="https://git.stickrouter.com/mike/N30pro/raw/branch/main/nx30pro512.bin"
FIRMWARE_NAME="nx30pro512.bin"
REMOTE_PATH="/tmp/${FIRMWARE_NAME}"

echo ""
echo "=================================================="
echo "  NX30Pro 一键升级脚本"
echo "  固件来源: Gitea"
echo "=================================================="
echo ""

# 检查剩余内存
FREE_MEM=$(free | awk '/Mem/{print $4}')
echo "[INFO] 当前可用内存: ${FREE_MEM}KB"

if [ "${FREE_MEM}" -lt 30000 ]; then
    echo "[WARN] 内存不足，尝试释放..."
    echo 3 > /proc/sys/vm/drop_caches
fi

# 下载固件
echo "[步骤 1/3] 下载固件到 ${REMOTE_PATH}..."
if [ -f "${REMOTE_PATH}" ]; then
    echo "[WARN] 已存在固件文件，跳过下载"
else
    wget -q --show-progress "${FIRMWARE_URL}" -O "${REMOTE_PATH}"
    if [ $? -ne 0 ]; then
        echo "[ERR] 固件下载失败，请检查网络"
        exit 1
    fi
fi

# 验证文件大小
SIZE=$(wc -c < "${REMOTE_PATH}")
echo "[INFO] 固件大小: ${SIZE} bytes"

if [ "${SIZE}" -lt 1000000 ]; then
    echo "[ERR] 固件文件异常，大小不正确"
    rm -f "${REMOTE_PATH}"
    exit 1
fi

echo "[步骤 2/3] 固件下载完成，准备升级..."
echo ""
echo "[WARN] 升级过程中请勿断电！"
echo "[WARN] 路由器将自动重启，升级完成后访问 http://192.168.6.66"
echo ""
echo "5秒后开始升级，按 Ctrl+C 取消..."
sleep 5

# 执行升级
echo "[步骤 3/3] 开始升级固件..."
sysupgrade -F -n "${REMOTE_PATH}"
