#!/bin/sh
# ============================================================
# ImmortalWrt 固件一键升级脚本
# 适用于 Redmi AC2100
# ============================================================

FIRMWARE_URL="https://git.stickrouter.com/mike/AC2100/src/branch/main/ac2100-op-lede.bin"
FIRMWARE_FILE="/tmp/ac2100-op-lede.bin"

echo "======================================================"
echo "   ImmortalWrt 固件升级工具 - Redmi AC2100"
echo "======================================================"
echo ""
echo "固件来源：$FIRMWARE_URL"
echo ""

# 检查磁盘空间
FREE_SPACE=$(df /tmp | tail -1 | awk '{print $4}')
if [ "$FREE_SPACE" -lt 20480 ]; then
    echo "[错误] /tmp 空间不足，需要至少 20MB"
    exit 1
fi

# 下载固件
echo "[1/3] 正在下载固件..."
wget --no-check-certificate -O "$FIRMWARE_FILE" "$FIRMWARE_URL"

if [ $? -ne 0 ] || [ ! -f "$FIRMWARE_FILE" ]; then
    echo "[错误] 固件下载失败，请检查网络连接"
    exit 1
fi

FILESIZE=$(ls -lh "$FIRMWARE_FILE" | awk '{print $5}')
echo "[OK] 固件下载完成，大小：$FILESIZE"
echo ""

# 确认升级
echo "======================================================"
echo "⚠️  警告："
echo "  - 升级后路由器将自动重启"
echo "  - 不保留任何配置（-n 参数）"
echo "  - 升级过程请勿断电，约需 2-3 分钟"
echo "  - 升级完成后 IP 变为 192.168.6.66"
echo "======================================================"
echo ""
printf "[?] 确认升级？(y/N): "
read CONFIRM

if [ "$CONFIRM" != "y" ] && [ "$CONFIRM" != "Y" ]; then
    echo "已取消升级"
    rm -f "$FIRMWARE_FILE"
    exit 0
fi

# 执行升级
echo ""
echo "[3/3] 开始升级，请勿断电..."
echo "SSH 连接将断开，请等待 2-3 分钟后重新连接 192.168.6.66"
echo ""
sysupgrade -F -n "$FIRMWARE_FILE"
