FROM oven/bun:1.3-slim

WORKDIR /app

# System deps for sqlite integrity checks + curl for healthcheck
RUN apt-get update && apt-get install -y --no-install-recommends sqlite3 curl ca-certificates && rm -rf /var/lib/apt/lists/*

COPY package.json bun.lock* ./
RUN bun install --frozen-lockfile || bun install

COPY client ./client
COPY server ./server
COPY drizzle ./drizzle
COPY space.json tsconfig.base.json bunfig.toml ./

# Build client + server
RUN bun run build

# Data & config dirs
RUN mkdir -p /app/data /app/backups

ENV PORT=3000
ENV NODE_ENV=production

EXPOSE 3000

# Volumes are declared in docker-compose.yml: ./data:/app/data and ./config.yaml:/app/config.yaml:ro
# Preserve data between builds: data/app.db is not deleted, WAL mode persisted via migration

HEALTHCHECK --interval=30s --timeout=5s --retries=3 --start-period=10s \
  CMD curl -sf http://localhost:3000/api/health || curl -sf http://localhost:${PORT:-3000}/api/health || exit 1

# Fix 1 – Dir perms hardening 770→700: ENTRYPOINT chmod 700 data backups before start, chmod 600 files
ENTRYPOINT ["sh","-c","chmod 700 /app/data /app/backups 2>/dev/null || chmod 700 data backups 2>/dev/null || true; chmod 600 /app/data/app.db /app/app.db /app/.env /app/backups/*.bak 2>/dev/null || chmod 600 data/app.db app.db .env backups/*.bak 2>/dev/null || true; exec bun run start"]
