#!/bin/bash
# Python共享库问题修复脚本

echo "=== Python共享库问题修复脚本 ==="

# 检测Python环境
echo "1. 检测Python环境..."
python3 --version
echo "Python路径: $(which python3)"

# 检测是否支持共享库
echo ""
echo "2. 检测共享库支持..."
if python3 -c "import sys; print('Shared library support:', hasattr(sys, 'getdlopenflags'))" 2>/dev/null; then
    echo "✓ Python支持共享库"
else
    echo "✗ Python不支持共享库"
fi

# 尝试方案一：使用修复的配置文件
echo ""
echo "3. 方案一：使用修复的配置文件打包..."

# 下载修复的配置文件
cat > build_noshared.spec << 'EOF'
# -*- mode: python ; coding: utf-8 -*-
# 适用于没有共享库的Python环境的PyInstaller配置

import sys
from pathlib import Path

# 项目根目录
ROOT_DIR = Path.cwd()

# 需要包含的数据文件
datas = [
    (str(ROOT_DIR / 'app'), 'app'),  # 包含整个app目录
    ('.env.example', '.'),           # 包含环境配置示例文件
]

# 可选数据文件（如果存在才包含）
optional_files = [
    ('database', 'database'),        # 包含数据库相关文件
]

# 添加可选数据文件
for src, dst in optional_files:
    src_path = ROOT_DIR / src
    if src_path.exists():
        datas.append((src, dst))
        print(f"包含可选数据文件: {src}")
    else:
        print(f"跳过可选数据文件: {src} (不存在)")

# 隐式导入的模块
hiddenimports = [
    'fastapi', 'uvicorn', 'starlette', 'pydantic', 'sqlalchemy',
    'passlib', 'python_jose', 'pymysql', 'redis', 'httpx', 'loguru',
    'python_dotenv', 'alembic', 'email.utils', 'yaml', 'toml',
    'json', 'base64', 'hashlib', 'datetime', 'uuid', 'os', 'sys',
    'pathlib', 'typing', 'collections', 'itertools', 'functools',
    'time', 'math', 're', 'socket', 'threading', 'asyncio',
    'cryptography', 'jinja2', 'mimetypes', 'tempfile', 'shutil',
    'argparse', 'codecs', 'encodings', 'random', 'secrets',
    'urllib', 'http', 'signal', 'multiprocessing'
]

block_cipher = None

a = Analysis(
    ['main.py'],
    pathex=[str(ROOT_DIR)],
    binaries=[],
    datas=datas,
    hiddenimports=hiddenimports,
    hookspath=[],
    hooksconfig={},
    runtime_hooks=[],
    excludes=[
        'Pillow', 'numpy', 'scipy', 'matplotlib', 'pandas',
        'torch', 'tensorflow', 'jupyter', 'notebook', 'ipython',
        'sphinx', 'pytest', 'setuptools', 'pip', 'wheel',
        'PyQt5', 'PyQt6', 'PySide2', 'PySide6', 'tkinter'
    ],
    win_no_prefer_redirects=False,
    win_private_assemblies=False,
    cipher=block_cipher,
    noarchive=False,
)

pyz = PYZ(a.pure, a.zipped_data, cipher=block_cipher)

exe = EXE(
    pyz,
    a.scripts,
    a.binaries,
    a.zipfiles,
    a.datas,
    [],
    name='cloud-drive-server',
    debug=False,
    bootloader_ignore_signals=False,
    strip=False,
    upx=False,
    upx_exclude=[],
    runtime_tmpdir=None,
    console=True,
    disable_windowed_traceback=False,
    argv_emulation=False,
    target_arch=None,
    codesign_identity=None,
    entitlements_file=None,
)
EOF

echo "✓ 已创建 build_noshared.spec"

# 尝试打包
echo "尝试使用修复配置打包..."
if pyinstaller --clean --noupx build_noshared.spec; then
    echo "✓ 方案一成功：可执行文件已生成"
    echo "文件位置: dist/cloud-drive-server"

    # 创建部署包
    mkdir -p deploy
    cp dist/cloud-drive-server deploy/
    cp .env.example deploy/

    # 创建启动脚本
    cat > deploy/start.sh << 'STARTEOF'
#!/bin/bash
cd "$(dirname "$0")"
if [ ! -f ".env" ]; then
    cp .env.example .env
fi
mkdir -p logs uploads
./cloud-drive-server
STARTEOF
    chmod +x deploy/start.sh

    echo "✓ 部署包已创建: deploy/"
    echo "现在可以运行: cd deploy && ./start.sh"
    exit 0
else
    echo "✗ 方案一失败"
fi

# 尝试方案二：单文件模式
echo ""
echo "4. 方案二：尝试单文件模式..."
if pyinstaller --clean --noupx --onefile main.py; then
    echo "✓ 方案二成功：单文件可执行文件已生成"

    mkdir -p deploy
    cp dist/main deploy/cloud-drive-server
    cp .env.example deploy/

    cat > deploy/start.sh << 'STARTEOF'
#!/bin/bash
cd "$(dirname "$0")"
if [ ! -f ".env" ]; then
    cp .env.example .env
fi
mkdir -p logs uploads
./cloud-drive-server
STARTEOF
    chmod +x deploy/start.sh

    echo "✓ 部署包已创建: deploy/"
    exit 0
else
    echo "✗ 方案二失败"
fi

# 尝试方案三：Python源代码部署
echo ""
echo "5. 方案三：创建Python源代码部署包..."

mkdir -p deploy
cp -r app deploy/
cp main.py deploy/
cp requirements.txt deploy/
cp .env.example deploy/

# 创建启动脚本
cat > deploy/start.sh << 'STARTEOF'
#!/bin/bash
cd "$(dirname "$0")"

# 检查Python环境
if ! command -v python3 &> /dev/null; then
    echo "错误: 未找到python3"
    exit 1
fi

# 检查虚拟环境
if [ ! -d "venv" ]; then
    echo "创建虚拟环境..."
    python3 -m venv venv
    source venv/bin/activate
    pip install -r requirements.txt
else
    source venv/bin/activate
fi

# 检查环境文件
if [ ! -f ".env" ]; then
    cp .env.example .env
    echo "已创建 .env 文件，请根据需要修改配置"
fi

# 创建必要目录
mkdir -p logs uploads

# 启动服务
echo "启动云盘后端服务..."
python main.py
STARTEOF

chmod +x deploy/start.sh

# 创建安装脚本
cat > deploy/install.sh << 'INSTALLEOF'
#!/bin/bash
INSTALL_DIR="$HOME/cloud-drive"
echo "安装云盘后端服务到 $INSTALL_DIR"
mkdir -p "$INSTALL_DIR"
cp -r * "$INSTALL_DIR/"
echo "安装完成！"
echo "进入目录: cd $INSTALED_DIR"
echo "启动服务: ./start.sh"
INSTALLEOF

chmod +x deploy/install.sh

echo "✓ 方案三成功：Python源代码部署包已创建"
echo "部署位置: deploy/"
echo "使用方法:"
echo "  1. cd deploy"
echo "  2. ./start.sh"

echo ""
echo "=== 修复完成 ==="
echo "建议使用方案三（Python源代码部署），这最稳定可靠。"