#!/bin/bash
# OpsMind AppStore 打包脚本
# 将 1Panel appstore 内容打包为 opsmind 格式
# 使用方法: bash build-appstore.sh

set -e
APPSTORE_SRC="/opt/appstore"
APPSTORE_OUT="/opt/appstore-serve"
NETWORK_NAME="opsmind-network"

echo "[1/4] 更新 appstore 源..."
cd "$APPSTORE_SRC" && git pull --quiet && echo "已更新到最新"

echo "[2/4] 替换网络名 1panel-network → $NETWORK_NAME..."
find "$APPSTORE_SRC/apps" -name "docker-compose.yml" -exec \
  sed -i "s/1panel-network/$NETWORK_NAME/g" {} \;

echo "[3/4] 打包所有 app 版本..."
mkdir -p "$APPSTORE_OUT/dev/opsmind"
count=0
for app_dir in "$APPSTORE_SRC/apps"/*/; do
    key=$(basename "$app_dir")
    for ver_dir in "$app_dir"*/; do
        [ -d "$ver_dir" ] || continue
        version=$(basename "$ver_dir")
        [[ "$version" =~ ^[0-9] ]] || continue
        dest_dir="$APPSTORE_OUT/dev/opsmind/$key/$version"
        mkdir -p "$dest_dir"
        tar_path="$dest_dir/${key}-${version}.tar.gz"
        cd "$APPSTORE_SRC/apps" && tar czf "$tar_path" "$key/$version/" 2>/dev/null
        count=$((count+1))
    done
done
echo "✅ 打包完成: $count 个版本"

echo "[4/4] 生成 opsmind.json..."
cd "$APPSTORE_SRC" && python3 /opt/appstore-serve/gen-opsmind-json.py

echo "✅ AppStore 构建完成"
