ARG ZAMMAD_VERSION=6.3.1

FROM node:22-slim as node

FROM zammad/zammad-docker-compose:${ZAMMAD_VERSION} AS builder
COPY --from=node /opt /opt
COPY --from=node /usr/local/bin /usr/local/bin
SHELL ["/bin/bash", "-e", "-o", "pipefail", "-c"]
WORKDIR ${ZAMMAD_DIR}
RUN mkdir -p /opt/zammad/contrib/link/addons
COPY addons contrib/link/addons
COPY setup.rb contrib/link/setup.rb
COPY install.rb contrib/link/install.rb

USER root
RUN sed -i '/script\/build\/cleanup\.sh/d' contrib/docker/setup.sh
RUN contrib/docker/setup.sh builder
ARG EMBEDDED=false
RUN if [ "$EMBEDDED" = "true" ] ; then sed -i '/proxy_set_header X-Forwarded-User "";/d' ${ZAMMAD_DIR}/contrib/nginx/zammad.conf; fi
RUN sed -i '/^[[:space:]]*# es config/a\
  echo "about to reinstall..."\n\
  bundle exec rails runner /opt/zammad/contrib/link/setup.rb\n\
  bundle exec rake zammad:package:migrate\n\
 ' /docker-entrypoint.sh
RUN ZAMMAD_SAFE_MODE=1 DATABASE_URL=postgresql://zammad:/zammad bundle exec rails runner /opt/zammad/contrib/link/install.rb
RUN ZAMMAD_SAFE_MODE=1 DATABASE_URL=postgresql://zammad:/zammad bundle exec rake assets:precompile

FROM zammad/zammad-docker-compose:${ZAMMAD_VERSION} as runner
USER ${ZAMMAD_USER}
COPY --from=builder --chown=zammad:zammad ${ZAMMAD_DIR} ${ZAMMAD_DIR}
COPY --from=builder /usr/local/bundle /usr/local/bundle
COPY --from=builder /docker-entrypoint.sh /docker-entrypoint.sh
