#!/usr/bin/env bash
# Server Manager - Linux 下用 PyInstaller 打包 main（与 build.bat 的 onedir 主程序对应）
# 用法: chmod +x build_linux.sh && ./build_linux.sh
# 产物: src/dist/main/main （可将该目录加入 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 main (onedir)..."
# add-data 在 Linux 下用冒号分隔
python3 -m PyInstaller --noconfirm --onedir --name main \
    "${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/main/config
if [[ -f config/tool.config ]]; then
    cp -f config/tool.config dist/main/config/tool.config || true
fi
if [[ -d "$RESOURCE_CONFIG" ]]; then
    cp -a "$RESOURCE_CONFIG/." dist/main/config/
    echo "  copied resources/config -> dist/main/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/main/main"
echo "CLI:  dist/main/main list"
echo "GUI:  dist/main/main"
echo "或设置 SERVER_MANAGER_MAIN 指向该文件，配合 scripts/run/run.sh 使用"
echo "============================================================"
echo
