#!/usr/bin/env bash
# 编排: 等模型(02)+小模型(03b)下完 -> 跑镜像(04) -> 重试失败镜像 -> 生成全局清单/校验 -> 打完成标记
set -uo pipefail
L=/srv/mirror/scripts/logs
mark(){ echo "[orch $(date +%H:%M:%S)] $*"; }

mark "waiting for 02_models + 03b_fix ..."
while pgrep -f "0[2]_models.sh|0[3]b_fix.sh" >/dev/null 2>&1; do sleep 30; done
mark "models+small done"

mark "verify model integrity (size vs ModelScope list)"
bash /srv/mirror/scripts/verify_models.sh > "$L/verify_models.log" 2>&1 || true

mark "images pass 1"
bash /srv/mirror/scripts/04_images.sh > "$L/04_images.log" 2>&1
mark "images pass 2 (retry failed pulls; existing tars skipped)"
bash /srv/mirror/scripts/04_images.sh > "$L/04_images_retry.log" 2>&1
mark "images done"

mark "global checksums for images/charts/installers"
( cd /srv/mirror/images     && sha256sum *.tar.zst > SHA256SUMS 2>/dev/null ) || true
( cd /srv/mirror/charts      && sha256sum *.tgz      > SHA256SUMS 2>/dev/null ) || true
( cd /srv/mirror/installers  && sha256sum *          > SHA256SUMS 2>/dev/null ) || true

{ echo "# file.liaoms.net mirror — $(date)";
  echo "## models";     du -sh --exclude=.cache /srv/mirror/models/qwen3* /srv/mirror/models/triton 2>/dev/null;
  echo "## images";     ls -lh /srv/mirror/images/*.tar.zst 2>/dev/null | awk '{print $5, $9}';
  echo "## charts";     ls /srv/mirror/charts/*.tgz 2>/dev/null | wc -l;
  echo "## installers"; ls /srv/mirror/installers 2>/dev/null | wc -l;
  echo "## pip";        ls /srv/mirror/pip/*.whl 2>/dev/null | wc -l;
  echo "## total";      du -sh /srv/mirror 2>/dev/null | cut -f1;
} > /srv/mirror/MANIFEST.txt

mark "ALL DONE"
touch "$L/FINISH.marker"
