# 使用多阶段构建在Linux环境下打包
FROM python:3.11-slim as builder

# 设置工作目录
WORKDIR /app

# 安装系统依赖
RUN apt-get update && apt-get install -y \
    build-essential \
    patchelf \
    && rm -rf /var/lib/apt/lists/*

# 复制打包脚本和配置
COPY build.spec build_linux.py requirements.txt requirements-build.txt ./

# 安装Python依赖
RUN pip install --no-cache-dir -r requirements-build.txt
RUN pip install --no-cache-dir -r requirements.txt

# 复制源代码
COPY . .

# 运行打包脚本
RUN python build_linux.py

# 最终阶段 - 准备部署包
FROM python:3.11-slim

# 安装运行时依赖
RUN apt-get update && apt-get install -y \
    curl \
    && rm -rf /var/lib/apt/lists/*

# 从构建阶段复制部署包
COPY --from=builder /app/deploy /opt/cloud-drive

# 设置工作目录
WORKDIR /opt/cloud-drive

# 创建非root用户
RUN useradd -r -s /bin/false cloud-drive && \
    chown -R cloud-drive:cloud-drive /opt/cloud-drive

# 暴露端口
EXPOSE 8000

# 切换到非root用户
USER cloud-drive

# 健康检查
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
  CMD curl -f http://localhost:8000/api/v1/health || exit 1

# 启动命令
CMD ["./cloud-drive-server"]