#!/bin/sh
# OTA 更新脚本 - 使用 curl 断点下载
# 用法: sh ota_curl.sh <下载URL>
# 示例: sh ota_curl.sh http://example.com/maix-t11-v2.15.1.zip

set -e

APP_DIR="/maixapp/apps/t11"
BACKUP_BASE="$APP_DIR/backups"
TMP_DIR="/tmp/ota_curl"
PENDING_FILE="$APP_DIR/ota_pending.json"

if [ $# -lt 1 ]; then
    echo "用法: $0 <下载URL>"
    exit 1
fi

OTA_URL="$1"
FILENAME=$(basename "$OTA_URL" | sed 's/?.*//')
[ -z "$FILENAME" ] && FILENAME="update.zip"

mkdir -p "$TMP_DIR" "$BACKUP_BASE"

# 1. 断点下载
echo "[OTA] 开始下载: $OTA_URL"
echo "[OTA] 保存到: $TMP_DIR/$FILENAME"
curl -C - -L --retry 3 --retry-delay 5 -o "$TMP_DIR/$FILENAME" "$OTA_URL"
echo "[OTA] 下载完成"

# 2. 备份当前目录
TIMESTAMP=$(date +%Y%m%d_%H%M%S 2>/dev/null || echo "00000000_000000")
BACKUP_DIR="$BACKUP_BASE/backup_$TIMESTAMP"
mkdir -p "$BACKUP_DIR"
echo "[OTA] 备份到: $BACKUP_DIR"
for f in "$APP_DIR"/*.py "$APP_DIR"/*.json "$APP_DIR"/*.xml "$APP_DIR"/*.yaml "$APP_DIR"/*.pem "$APP_DIR"/*.mud "$APP_DIR"/*.so "$APP_DIR"/S99archery; do
    [ -f "$f" ] && cp "$f" "$BACKUP_DIR/"
done
echo "[OTA] 备份完成"

# 3. 解压并替换文件
echo "[OTA] 开始更新..."
if echo "$FILENAME" | grep -qi '\.zip$'; then
    unzip -q -o "$TMP_DIR/$FILENAME" -d "$APP_DIR/"
else
    cp "$TMP_DIR/$FILENAME" "$APP_DIR/"
fi
sync

# 4. 写入 pending 文件（用于崩溃恢复）
echo '{"ts":0,"url":"'"$OTA_URL"'","backup_dir":"'"$BACKUP_DIR"'","restart_count":0,"max_restarts":3}' > "$PENDING_FILE"
sync

echo "[OTA] 更新完成，准备重启..."

# 5. 重启
sleep 1
reboot
