# 使用官方 Ruby 镜像作为基础镜像
FROM ruby:3.1-bullseye

# 设置镜像源（提高国内网络访问速度）
RUN sed -i 's/deb.debian.org/mirrors.ustc.edu.cn/g' /etc/apt/sources.list \
    && sed -i 's/security.debian.org/mirrors.ustc.edu.cn/g' /etc/apt/sources.list

# 安装系统依赖
RUN apt-get update && apt-get install -y \
    curl \
    gnupg \
    build-essential \
    libxml2-dev \
    libxslt1-dev \
    pkg-config \
    wget \
    && rm -rf /var/lib/apt/lists/*

# 安装 Node.js 16 (LTS) - 使用官方二进制包，增加重试机制
RUN for i in 1 2 3; do \
        curl -fsSL --connect-timeout 10 --max-time 300 \
        https://nodejs.org/dist/v16.20.2/node-v16.20.2-linux-x64.tar.xz -o node.tar.xz \
        && break || sleep 5; \
    done \
    && tar -xJf node.tar.xz -C /usr/local --strip-components=1 \
    && rm node.tar.xz \
    && ln -s /usr/local/bin/node /usr/local/bin/nodejs

# 设置工作目录
WORKDIR /app

# 复制 vendor 目录（包含本地gems）
COPY vendor ./vendor

# 复制 Gemfile 和 package.json 先安装依赖（利用 Docker 缓存）
COPY Gemfile Gemfile.lock ./
COPY package.json package-lock.json ./

# 配置npm使用国内镜像源（提高网络访问速度）
RUN npm config set registry https://registry.npmmirror.com/ \
    && npm config set timeout 60000 \
    && npm config set network-timeout 300000

# 配置bundle使用国内gem源
RUN bundle config mirror.https://rubygems.org https://gems.ruby-china.com

# 安装 Ruby 依赖（不使用 deployment 模式避免版本冲突）
RUN bundle config set --local without 'development test' \
    && bundle install --retry=3

# 安装 Node.js 依赖（使用重试机制）
RUN npm install --production --retry=3 || \
    (npm config set registry https://registry.npmjs.org/ && npm install --production --retry=3)

# 复制项目文件
COPY . .

# 创建必要的目录
RUN mkdir -p uploads public

# 设置文件权限
RUN chmod +x entrypoint.sh

# 暴露端口
EXPOSE 3000

# 设置启动脚本
ENTRYPOINT ["./entrypoint.sh"]

# 默认命令
CMD ["npm", "start"] 