#!/bin/bash
# gen-manifest.sh — 生成 APK 发行版 manifest
# 在 Android Studio 构建 Release APK 后运行
# 用法: bash gen-manifest.sh 6 stable
#       bash gen-manifest.sh 6 all

set -e

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

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

OTA_DIR="$(dirname "$0")"
APK_PATH="$OTA_DIR/../packages/client-android/android/app/build/outputs/apk/debug/v0.1.0-dav-android-${VER}-debug.apk"
BASE="https://git.childish-ghost.com/LukeMackin/Yuzu-GCA"
TAG="v0.1.0-dav-android-${VER}"
APK_NAME="v0.1.0-dav-android-${VER}-debug.apk"
DL_URL="${BASE}/releases/download/${TAG}/${APK_NAME}"

if [ ! -f "$APK_PATH" ]; then
  echo "APK not found: $APK_PATH"
  exit 1
fi

SHA256=$(sha256sum "$APK_PATH" | cut -d' ' -f1)
echo "APK  : $APK_PATH"
echo "SHA256: $SHA256"

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

echo ""
echo "Next: git tag $TAG && git push --tags"
echo "      Gitea Release → upload APK"
echo "      bash push-hotfix.sh $VER stable  # H5同步"
