# Build frontend
FROM node:22-alpine AS frontend-builder
WORKDIR /app/web
COPY web/package.json web/pnpm-lock.yaml ./
RUN npm install -g pnpm && pnpm install --frozen-lockfile
COPY web/ .
RUN pnpm build

# Build backend
FROM golang:1.24-alpine AS backend-builder
WORKDIR /app
RUN apk add --no-cache git
ENV GOTOOLCHAIN=auto
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 GOOS=linux go build -o /taskpool .

# Production stage
FROM alpine:3.19

# 注意：PATH 必须保留 /sbin:/usr/sbin，否则 alpine 的 apk 找不到
ENV TZ=Asia/Shanghai \
    MISE_DATA_DIR=/app/envs/mise \
    MISE_CONFIG_DIR=/app/envs/mise \
    MISE_HIDE_UPDATE_WARNING=1 \
    PATH="/app/envs/mise/shims:/app/envs/mise/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"

RUN apk add --no-cache \
      nginx supervisor bash curl wget ca-certificates tzdata git rsync openssh-client \
  && cp /usr/share/zoneinfo/${TZ} /etc/localtime \
  && echo "${TZ}" > /etc/timezone \
  && curl https://mise.run | MISE_INSTALL_PATH=/usr/local/bin/mise sh \
  && chmod +x /usr/local/bin/mise \
  && mkdir -p /app/envs/mise \
  && mise --version

# Copy frontend
COPY --from=frontend-builder /app/web/dist /usr/share/nginx/html

# Copy backend
COPY --from=backend-builder /taskpool /app/taskpool

# Copy nginx config (modified for localhost)
COPY nginx-standalone.conf /etc/nginx/http.d/default.conf

# Copy supervisor config + backend wrapper (logs go to docker logs)
COPY supervisord.conf /etc/supervisord.conf
COPY docker/start-backend.sh /app/start-backend.sh

# Create data directories and ship example config (used when no volume config)
COPY configs/config.example.ini /app/configs/config.example.ini
RUN mkdir -p /app/data /app/configs /app/envs /app/logs /app/data/scripts \
  && chmod +x /app/taskpool /app/start-backend.sh \
  && ln -sf /app/taskpool /usr/local/bin/taskpool

WORKDIR /app
EXPOSE 3000 8052

CMD ["/usr/bin/supervisord", "-c", "/etc/supervisord.conf"]
