#!/usr/bin/env bash
# Server Manager - Linux 下用 PyInstaller 打包 ServerManager（与 build.bat 的 onedir 主程序对应）
# 用法: chmod +x build_linux.sh && ./build_linux.sh
# 产物: src/dist/ServerManager/ServerManager （可将该目录加入 PATH，或设置 SERVER_MANAGER_MAIN 供 scripts/run/run.sh 自动调用）

set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
SRC="$ROOT/src"
RESOURCE_CONFIG="$ROOT/resources/config"
cd "$SRC"

echo "============================================================"
echo "         Server Manager - build Linux (PyInstaller onedir)"
echo "============================================================"
echo

if ! command -v python3 >/dev/null 2>&1; then
    echo "[ERROR] Need python3"
    exit 1
fi

echo "[1/5] pip deps..."
python3 -m pip install -q PyQt6 pyinstaller pymysql Pillow requests

echo "[2/5] icon..."
python3 "$ROOT/resources/icon/convert_icon.py" || true

ICON_ARG=(--icon NONE)
if [[ -f "$ROOT/resources/icon/icon.ico" ]]; then
    ICON_ARG=(--icon "$ROOT/resources/icon/icon.ico")
fi

echo "[3/5] clean dist/build..."
rm -rf dist build ./*.spec 2>/dev/null || true

echo "[4/5] PyInstaller ServerManager (onedir)..."
# add-data 在 Linux 下用冒号分隔
python3 -m PyInstaller --noconfirm --onedir --name ServerManager \
    "${ICON_ARG[@]}" \
    --add-data "$ROOT/resources/version.json:." \
    --add-data "$ROOT/resources/config.json:." \
    --add-data "$ROOT/resources/icon:icon" \
    --hidden-import PyQt6.QtWidgets \
    --hidden-import PyQt6.QtCore \
    --hidden-import PyQt6.QtGui \
    --hidden-import pymysql \
    --hidden-import entrypoints.cli.main \
    --hidden-import entrypoints.cli.extended \
    --hidden-import entrypoints.gui.bootstrap \
    --hidden-import mcp.server \
    --hidden-import mcp.tools \
    --hidden-import models.app_config \
    --hidden-import services.commands \
    --hidden-import services.server_creator \
    --hidden-import services.hot_update \
    --hidden-import services.rg_search \
    --hidden-import bsdiff4 \
    --collect-all bsdiff4 \
    --hidden-import requests \
    entrypoints/main.py

echo "[5/5] done."
mkdir -p dist/ServerManager/config
if [[ -f config/user.config ]]; then
    cp -f config/user.config dist/ServerManager/config/user.config || true
fi
if [[ -d "$RESOURCE_CONFIG" ]]; then
    cp -a "$RESOURCE_CONFIG/." dist/ServerManager/config/
    echo "  copied resources/config -> dist/ServerManager/config"
else
    echo "  [WARN] resources/config missing"
fi

rm -rf build 2>/dev/null || true
rm -f ./*.spec 2>/dev/null || true

echo
echo "============================================================"
echo "OK: dist/ServerManager/ServerManager"
echo "CLI:  dist/ServerManager/ServerManager list"
echo "GUI:  dist/ServerManager/ServerManager"
echo "或设置 SERVER_MANAGER_MAIN 指向该文件，配合 scripts/run/run.sh 使用"
echo "============================================================"
echo
