# syntax=docker/dockerfile:1

# ============================================================
# Stage 1 — PHP dependencies (Composer)
# ============================================================
FROM composer:2 AS vendor
WORKDIR /app
COPY composer.json composer.lock symfony.lock ./
# --no-scripts: the Symfony kernel isn't fully copied yet; scripts run later in entrypoint.
#
# The Coolify build host intermittently gets HTTP 400 from codeload.github.com
# when Composer pulls dist zips. Mitigations:
#   - bump Composer's own HTTP retry count
#   - wrap the whole install in a retry loop
#   - on the final attempt, fall back to --prefer-source (git clone) which uses
#     a different endpoint than codeload dist zips
ENV COMPOSER_HTTP_RETRIES=5
RUN set -eu; \
    for i in 1 2 3 4 5; do \
        composer install --no-dev --no-scripts --no-interaction \
            --prefer-dist --optimize-autoloader --ignore-platform-reqs && exit 0; \
        echo "composer install failed (attempt $i) — retrying in 5s"; \
        sleep 5; \
    done; \
    echo "dist download kept failing — final attempt via --prefer-source"; \
    composer install --no-dev --no-scripts --no-interaction \
        --prefer-source --optimize-autoloader --ignore-platform-reqs

# ============================================================
# Stage 2 — Frontend assets (Webpack Encore / React 19)
# ============================================================
FROM node:22-alpine AS assets
WORKDIR /app
# vendor is required: package.json references "@symfony/ux-react": "file:vendor/symfony/ux-react/assets"
COPY --from=vendor /app/vendor ./vendor
COPY package.json yarn.lock ./
RUN yarn install --frozen-lockfile
COPY webpack.config.js postcss.config.js tsconfig.json ./
COPY assets ./assets
COPY public ./public
RUN yarn build   # outputs to public/build

# ============================================================
# Stage 3 — Runtime (PHP-FPM + Nginx via Supervisor)
# ============================================================
FROM php:8.2-fpm-alpine AS runtime

# System deps + PHP extensions.
#   pdo_mysql -> MariaDB,  intl -> Symfony,  opcache -> perf,  redis -> Messenger/cache transport
#
# IMPORTANT: the Coolify build host cannot reach pecl.php.net (the redis package
# registry) — both `pecl install redis` and install-php-extensions failed there
# with `No releases available for package "pecl.php.net/redis"`. So redis is
# built directly from its GitHub source tarball instead (github.com IS
# reachable). pdo_mysql/intl/opcache are bundled with PHP and need no network.
# retry() guards the apk/github fetches against transient mirror drops.
#
# intl is C++ and slow to compile; Coolify builds with --no-cache so it recompiles
# every deploy and was overrunning the build timeout (exit 255). Compile in
# parallel across all cores (MAKEFLAGS=-j$(nproc)) to cut that time several-fold.
ENV PHPREDIS_VERSION=6.1.0
RUN set -eu; \
    export MAKEFLAGS="-j$(nproc)"; \
    retry() { for i in 1 2 3 4 5; do "$@" && return 0; echo "retry $i: $*"; sleep 5; done; return 1; }; \
    retry apk add --no-cache nginx supervisor icu-libs \
 && retry apk add --no-cache --virtual .build-deps $PHPIZE_DEPS icu-dev \
 && docker-php-ext-install pdo_mysql intl opcache \
 && retry curl -sSLf "https://github.com/phpredis/phpredis/archive/refs/tags/${PHPREDIS_VERSION}.tar.gz" -o /tmp/phpredis.tar.gz \
 && mkdir -p /usr/src/php/ext/redis \
 && tar -xf /tmp/phpredis.tar.gz -C /usr/src/php/ext/redis --strip-components=1 \
 && docker-php-ext-install redis \
 && rm -rf /tmp/phpredis.tar.gz \
 && apk del .build-deps

WORKDIR /app

# Application source.
COPY . .
# Built dependencies from earlier stages (overwrite anything from the source copy).
COPY --from=vendor /app/vendor ./vendor
COPY --from=assets /app/public/build ./public/build

# Symfony's Dotenv::bootEnv() hard-requires a .env file to exist, even in prod.
# The repo's .env is gitignored (it holds dev secrets), so Coolify's clone has
# none and the app fatals with "Unable to read /app/.env". Write a minimal prod
# .env if one wasn't copied in — every real value still comes from the compose
# environment (clear_env=no lets it through), and Dotenv never overwrites an
# already-set env var, so this only satisfies the file-existence requirement.
RUN [ -f .env ] || printf 'APP_ENV=prod\nAPP_DEBUG=0\n' > .env

# Container configuration.
COPY docker/php/php.ini /usr/local/etc/php/conf.d/zz-app.ini
COPY docker/php/opcache.ini /usr/local/etc/php/conf.d/zz-opcache.ini
COPY docker/php/zz-pool.conf /usr/local/etc/php-fpm.d/zz-pool.conf
COPY docker/nginx/default.conf /etc/nginx/http.d/default.conf
COPY docker/supervisord.conf /etc/supervisor/conf.d/supervisord.conf
COPY docker/entrypoint.sh /usr/local/bin/entrypoint.sh

COPY docker/healthcheck.sh /usr/local/bin/healthcheck.sh

# Make nginx run as the non-root www-data user:
#  - drop the `user nginx;` directive (ignored + warns when master isn't root)
#  - put the pid file in a www-data-writable path (default /run/nginx is root-only)
RUN sed -i '/^user /d' /etc/nginx/nginx.conf \
 && sed -i '1i pid /tmp/nginx.pid;' /etc/nginx/nginx.conf

RUN chmod +x /usr/local/bin/entrypoint.sh /usr/local/bin/healthcheck.sh \
 && mkdir -p var/cache var/log var/uploads public/uploads config/jwt \
 # Source may be copied with restrictive (0600) host perms; ensure the runtime
 # user (www-data) can read all app files — opcache preload runs as www-data
 # and otherwise fails with "Permission denied" on /app/config/preload.php.
 && chmod -R a+rX /app \
 && chown -R www-data:www-data var public/uploads config/jwt \
 # nginx (run as www-data) needs to write its temp/cache/log dirs.
 && chown -R www-data:www-data /var/lib/nginx /var/log/nginx 2>/dev/null || true

# Drop privileges: the entrypoint, supervisord, php-fpm and nginx all run as
# www-data. nginx binds 8080 (non-privileged) so root is never required.
USER www-data

EXPOSE 8080
HEALTHCHECK --interval=15s --timeout=5s --retries=5 --start-period=60s \
    CMD ["/usr/local/bin/healthcheck.sh"]
ENTRYPOINT ["/usr/local/bin/entrypoint.sh"]
CMD ["supervisord", "-c", "/etc/supervisor/conf.d/supervisord.conf"]
