ARG DEBIAN_RELEASE=trixie
ARG ALPINE_RELEASE=3.24

# Copy this target into an existing PHP application without the standalone
# web server or its automatic session bootstrap.
FROM scratch AS assets
COPY src/pictory /var/www/revpi/pictory
COPY usr/bin/pictory_configcheck /usr/bin/pictory_configcheck

# Compatibility target for integrations that depend on Debian packages.
FROM debian:${DEBIAN_RELEASE}-slim AS debian

RUN apt-get update \
    && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \
        apache2 \
        libapache2-mod-php \
        python3 \
    && rm -rf /var/lib/apt/lists/* /var/www/html/* \
    && a2enmod headers \
    && ln -sf /proc/self/fd/1 /var/log/apache2/access.log \
    && ln -sf /proc/self/fd/2 /var/log/apache2/error.log

# Keep the same application path as on RevPi for pictory_configcheck.
COPY --from=assets /var/www/revpi/pictory /var/www/revpi/pictory
COPY --from=assets /usr/bin/pictory_configcheck /usr/bin/pictory_configcheck
RUN find /var/www/revpi/pictory -perm /022 -exec chmod go-w {} + \
    && chown -R www-data:www-data \
        /var/www/revpi/pictory/projects /var/www/revpi/pictory/export

COPY docker/apache.conf /etc/apache2/sites-available/000-default.conf
COPY docker/session-helper.php /var/www/html/index.php
COPY docker/redirect.html /var/www/html/index.html
COPY --chmod=755 docker/entrypoint.sh /usr/local/bin/pictory-entrypoint

ENV PICTORY_AUTH_USER_HEADER="" \
    PICTORY_COOKIE_SECURE=0

EXPOSE 80
ENTRYPOINT ["pictory-entrypoint"]
CMD ["apache2", "-D", "FOREGROUND"]

# Default runtime: Alpine packages avoid Debian's Perl and packaging overhead.
FROM alpine:${ALPINE_RELEASE} AS standalone

RUN apk add --no-cache apache2 php84-apache2 php84-session python3 \
    && addgroup -S -g 33 pictory \
    && adduser -S -D -H -u 33 -G pictory pictory \
    && sed -i 's/^User apache$/User pictory/; s/^Group apache$/Group pictory/' \
        /etc/apache2/httpd.conf \
    && mkdir -p /var/www/html /var/lib/pictory/sessions \
    && chown pictory:pictory /var/lib/pictory/sessions \
    && chmod 700 /var/lib/pictory/sessions \
    && ln -sf /proc/self/fd/1 /var/log/apache2/access.log \
    && ln -sf /proc/self/fd/2 /var/log/apache2/error.log

COPY --from=assets /var/www/revpi/pictory /var/www/revpi/pictory
COPY --from=assets /usr/bin/pictory_configcheck /usr/bin/pictory_configcheck
RUN find /var/www/revpi/pictory -perm /022 -exec chmod go-w {} + \
    && chown -R pictory:pictory \
        /var/www/revpi/pictory/projects /var/www/revpi/pictory/export

COPY docker/apache.conf /etc/apache2/conf.d/pictory.conf
COPY docker/php.ini /etc/php84/conf.d/99-pictory.ini
COPY docker/session-helper.php /var/www/html/index.php
COPY docker/redirect.html /var/www/html/index.html
COPY --chmod=755 docker/entrypoint.sh /usr/local/bin/pictory-entrypoint

ENV PICTORY_AUTH_USER_HEADER="" \
    PICTORY_COOKIE_SECURE=0

EXPOSE 80
ENTRYPOINT ["pictory-entrypoint"]
CMD ["httpd", "-D", "FOREGROUND"]
