#!/bin/bash
set -e

# 配置参数
REPO="oppen321/ZeroWrt-Action"

# 1. 下载GitHub Release文件
echo "➜ 下载GitHub Release文件..."

# 检查model参数是否有效
if [ "$model" != "x86_64" ] && [ "$model" != "rockchip" ]; then
    echo "❌ 未指定有效的model参数 (x86_64 或 rockchip)"
    exit 1
fi

# 根据架构选择对应的tag
if [ "$model" = "x86_64" ]; then
    TAG="OpenWrt-X86_64-24.10"
else
    TAG="OpenWrt-Rockchip-24.10"
fi

# 获取release的assets
RELEASE_URL="https://api.github.com/repos/${REPO}/releases/tags/${TAG}"

# 添加GitHub API认证头（推荐使用）
HEADERS=(
    -H "Accept: application/vnd.github.v3+json"
    -H "Authorization: token ${GITHUB_TOKEN:-}"  # 使用环境变量中的token
)

# 获取assets下载链接
echo "正在获取发布资源..."
ASSETS=$(curl -sSL "${HEADERS[@]}" "$RELEASE_URL" | jq -r '.assets[]?.browser_download_url' 2>/dev/null)

if [ -z "$ASSETS" ]; then
    echo "❌ 未找到对应release的assets文件，可能原因："
    echo "   - tag名称不正确: ${TAG}"
    echo "   - 仓库中没有该tag的release"
    echo "   - API请求被限制（尝试添加GitHub token）"
    echo "   - jq解析失败，请确保已安装jq"
    exit 1
fi

# 创建下载目录
DOWNLOAD_DIR="./downloads"
mkdir -p "$DOWNLOAD_DIR"
cd "$DOWNLOAD_DIR" || exit 1

# 下载所有assets
echo "开始下载文件..."
for url in $ASSETS; do
    filename=$(basename "$url")
    echo "正在下载: $filename"
    if ! wget -q --show-progress "$url"; then
        echo "⚠️ 下载失败: $filename"
        continue
    fi
done

# 重命名文件（更安全的实现）
echo "重命名文件..."
for file in openwrt*; do
    if [ -e "$file" ]; then
        newname="zerowrt-plus-${date}${file#openwrt}"
        echo "重命名: $file → $newname"
        mv -- "$file" "$newname"
    fi
done

echo "✅ 下载和重命名完成"