#!/bin/bash
# push-hotfix.sh — 推送 H5 热更新补丁到 Gitea
#
# 用法:
#   ./push-hotfix.sh 7 stable        # 只更新 stable 渠道
#   ./push-hotfix.sh 7 all           # 更新全部三个渠道
#   ./push-hotfix.sh 7 beta nightly  # 更新指定渠道
#
# 流程:
#   1. 创建 ota/h5/index-v{VER}.html（如果不存在则从模板生成）
#   2. 计算 SHA256
#   3. 更新 ota/h5-manifest-{CHANNEL}.json
#   4. 如果是稳定版，更新 ota/version.txt
#   5. git add + commit + push

set -e

VER="$1"
shift
CHANNELS=("$@")

if [ -z "$VER" ] || [ ${#CHANNELS[@]} -eq 0 ]; then
  echo "用法: $0 <版本号> <渠道...>"
  echo "示例: $0 7 stable beta nightly"
  exit 1
fi

OTA_DIR="$(dirname "$0")"
H5_DIR="$OTA_DIR/h5"
BASE_URL="https://git.childish-ghost.com/LukeMackin/Yuzu-GCA/raw/branch/main/ota"

# 1. 创建 HTML 文件（如果不存在）
HTML_FILE="$H5_DIR/index-v${VER}.html"
if [ ! -f "$HTML_FILE" ]; then
  echo "→ 请手动创建 $HTML_FILE 或从 index-v6.html 复制修改"
  exit 1
fi

# 2. 计算 SHA256
SHA256=$(sha256sum "$HTML_FILE" | cut -d' ' -f1)
echo "SHA256: $SHA256"

# 3. 更新 manifest
FULL_URL="${BASE_URL}/h5/index-v${VER}.html"

for CH in "${CHANNELS[@]}"; do
  if [ "$CH" = "all" ]; then
    for CH in stable beta nightly; do
      MANIFEST="$OTA_DIR/h5-manifest-${CH}.json"
      cat > "$MANIFEST" <<EOF
{"latest":"0.1.0-dav-android-${VER}","min_version":"0.1.0-dav-android-5","url":"${FULL_URL}","sha256":"${SHA256}"}
EOF
      echo "  ✓ h5-manifest-${CH}.json"
    done
    break
  fi
  MANIFEST="$OTA_DIR/h5-manifest-${CH}.json"
  cat > "$MANIFEST" <<EOF
{"latest":"0.1.0-dav-android-${VER}","min_version":"0.1.0-dav-android-5","url":"${FULL_URL}","sha256":"${SHA256}"}
EOF
  echo "  ✓ h5-manifest-${CH}.json"
done

# 4. 稳定版更新 version.txt
if [[ " ${CHANNELS[*]} " =~ " stable " ]] || [[ " ${CHANNELS[*]} " =~ " all " ]]; then
  echo "0.1.0-dav-android-${VER}|${FULL_URL}|${SHA256}" > "$OTA_DIR/version.txt"
  echo "  ✓ version.txt"
fi

# 5. git push
echo ""
echo "commit & push?"
read -p "(y/N) " yn
if [ "$yn" = "y" ] || [ "$yn" = "Y" ]; then
  git add "$OTA_DIR"
  git commit -m "hotfix: v${VER} → ${CHANNELS[*]}"
  git push
  echo "✓ pushed"
fi
