#!/bin/bash
# 下载池核 Poolrooms 开发起步包：下载全部分卷 → 校验 → 合并 → 校验整包 → 解压到 ./poolrooms
# 用法：KIT_BASE=https://你的地址 bash fetch_kit.sh     （KIT_BASE = 放 parts.txt / SHA256SUMS.txt / 分卷的目录 URL）
# 需要：curl、sha256sum（macOS 用 shasum -a 256，脚本会自动选）、unzip
set -euo pipefail
KIT_BASE="${KIT_BASE:-https://poolrooms-kit-5c043c.pages.dev}"
KIT_BASE="${KIT_BASE%/}"
DEST="${DEST:-.}"
WORK="$DEST/.poolrooms_kit_dl"
if command -v sha256sum >/dev/null; then SHA="sha256sum"; else SHA="shasum -a 256"; fi
case "$KIT_BASE" in https://poolrooms-kit-5c043c.pages.dev*) echo "请先设置 KIT_BASE，例如：KIT_BASE=https://example.com/kit bash fetch_kit.sh" >&2; exit 2;; esac
mkdir -p "$WORK"; cd "$WORK"
get() { curl -fsSL --retry 5 --retry-delay 3 -C - -o "$1" "$KIT_BASE/$1"; }
echo "[1/5] 清单"; curl -fsSL --retry 5 -o parts.txt "$KIT_BASE/parts.txt"; curl -fsSL --retry 5 -o SHA256SUMS.txt "$KIT_BASE/SHA256SUMS.txt"; curl -fsSL --retry 5 -o ZIP_SHA256.txt "$KIT_BASE/ZIP_SHA256.txt"
N=$(grep -c . parts.txt); echo "      共 $N 个分卷"
echo "[2/5] 下载分卷"
while read -r p; do
  [ -z "$p" ] && continue
  if [ -f "$p" ] && grep " $p\$" SHA256SUMS.txt | $SHA -c --status 2>/dev/null; then echo "      $p 已存在且校验通过"; continue; fi
  rm -f "$p"; echo "      $p"; get "$p"
done < parts.txt
echo "[3/5] 校验分卷"; $SHA -c SHA256SUMS.txt
echo "[4/5] 合并并校验整包"
ZIP=$(awk '{print $2}' ZIP_SHA256.txt | sed 's/^\*//'); : > "$ZIP"
while read -r p; do [ -n "$p" ] && cat "$p" >> "$ZIP"; done < parts.txt
$SHA -c ZIP_SHA256.txt
echo "[5/5] 解压"; cd - >/dev/null; unzip -q -o "$WORK/$ZIP" -d "$DEST"
echo "完成：$(cd "$DEST/poolrooms" && pwd)  —— 先读 docs/START.md"
echo "（下载缓存在 $WORK，确认无误后可删除）"
