FROM node:latest AS base

# Install dependencies only when needed
FROM base AS deps
WORKDIR /app

# Install dependencies based on the preferred package manager
COPY bookie/package.json bookie/yarn.lock* bookie/package-lock.json* bookie/pnpm-lock.yaml* ./
RUN \
  if [ -f yarn.lock ]; then yarn --frozen-lockfile; \
  elif [ -f package-lock.json ]; then npm ci; \
  elif [ -f pnpm-lock.yaml ]; then corepack enable pnpm && pnpm i --frozen-lockfile; \
  else echo "Lockfile not found." && exit 1; \
  fi

FROM base as builder
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY /bookie ./

RUN \
  if [ -f yarn.lock ]; then yarn run build; \
  elif [ -f package-lock.json ]; then npm run build; \
  elif [ -f pnpm-lock.yaml ]; then corepack enable pnpm && pnpm run build; \
  else echo "Lockfile not found." && exit 1; \
  fi

FROM python:3.12 AS runner
LABEL maintainer="Amritanshu <docker@tanshu.com>"

RUN apt-get update && \
    apt-get install -y locales && \
    sed --in-place --expression='s/# en_IN UTF-8/en_IN UTF-8/' /etc/locale.gen && \
    dpkg-reconfigure --frontend=noninteractive locales

ENV LANG en_IN
ENV LC_ALL en_IN

# Install Poetry
RUN curl -sSL https://install.python-poetry.org | POETRY_HOME=/opt/poetry python - && \
    cd /usr/local/bin && \
    ln -s /opt/poetry/bin/poetry && \
    poetry config virtualenvs.create false

WORKDIR /app

COPY barker/pyproject.toml /app/pyproject.toml

# Allow installing dev dependencies to run tests
ARG INSTALL_DEV=false
RUN bash -c "if [ $INSTALL_DEV == 'true' ] ; then poetry install --no-root ; else poetry install --no-root --only main ; fi"

COPY /barker ./
COPY --from=builder /frontend/browser /app/frontend

ENV PYTHONPATH=/app
EXPOSE 80
VOLUME /frontend

RUN chmod 777 /app/docker-entrypoint.sh \
    && ln -s /app/docker-entrypoint.sh /usr/local/bin/docker-entrypoint.sh \
    && ln -s /app/docker-entrypoint.sh /
ENTRYPOINT ["docker-entrypoint.sh"]

CMD ["poetry", "run", "/app/run.sh"]