# Alpine-based PHP 7.4 FPM image optimized for WordPress
ARG BASE_VERSION=7.4
ARG BASE_TAG=${BASE_VERSION}-fpm-alpine3.16
FROM php:${BASE_TAG}
ARG BASE_VERSION

# Install build dependencies, PHP extensions, and runtime dependencies in a single layer
RUN set -eux; \
	apk add --no-cache --virtual .build-deps \
	$PHPIZE_DEPS \
	autoconf \
	gcc \
	g++ \
	make \
	pkgconfig \
	freetype-dev \
	libjpeg-turbo-dev \
	libpng-dev \
	libxml2-dev \
	zlib-dev \
	icu-dev \
	libzip-dev \
	oniguruma-dev \
	mariadb-dev \
	; \
	\
	# Install runtime dependencies
	apk add --no-cache \
	bash \
	curl \
	freetype \
	libjpeg-turbo \
	libpng \
	libxml2 \
	zlib \
	icu-libs \
	libzip \
	mariadb-client \
	openssl \
	ca-certificates \
	tzdata \
	; \
	update-ca-certificates; \
	\
	# Configure and install extensions
	docker-php-ext-configure gd --with-freetype --with-jpeg; \
	docker-php-ext-install -j"$(nproc)" \
	gd \
	mysqli \
	pdo \
	pdo_mysql \
	zip \
	exif \
	intl \
	bcmath \
	opcache \
	xml \
	mbstring \
	xmlrpc \
	soap \
	pcntl \
	; \
	\
	# Install PECL extensions
	pecl channel-update pecl.php.net; \
	pecl install redis && docker-php-ext-enable redis; \
	\
	# Use production php.ini
	cp "$PHP_INI_DIR/php.ini-production" "$PHP_INI_DIR/php.ini"; \
	\
	# Install WP-CLI for remedial administration
	curl -fSL https://raw.githubusercontent.com/wp-cli/builds/gh-pages/phar/wp-cli.phar -o /usr/local/bin/wp; \
	chmod +x /usr/local/bin/wp; \
	\
	# Clean up build dependencies
	apk del .build-deps; \
	rm -rf /var/cache/apk/* /tmp/*

# Create a non-root application user and prepare webroot directory
RUN addgroup -g 1000 app && \
	adduser -D -u 1000 -G app app && \
	mkdir -p /var/www/html && \
	chown -R app:app /var/www/html && \
	mkdir -p /var/run/php /run/php /var/log/php && \
	chown -R app:app /var/run/php /run/php /var/log/php

# Ship opinionated PHP configuration snippets from source control
COPY php-fpm/conf.d/ /usr/local/etc/php/conf.d/

# Copy the force-debug script (enablement is handled via conf.d/99-force-debug.ini)
COPY --chown=app:app shared/php-fpm/force-debug.php /usr/local/etc/php/force-debug.php

# Copy shared healthcheck assets
RUN mkdir -p /usr/local/share/auvem/health
COPY shared/php-fpm/healthcheck.php /usr/local/share/auvem/health/healthcheck.php

# Copy pool configuration from this directory
COPY --chown=app:app php-fpm/${BASE_VERSION}/www.conf /usr/local/etc/php-fpm.d/www.conf
# Copy the global php-fpm configuration so logging defaults are predictable
COPY php-fpm/${BASE_VERSION}/php-fpm.conf /usr/local/etc/php-fpm.conf

# Copy entrypoint from shared path in repo root
COPY --chown=root:root shared/php-fpm/entrypoint.sh /usr/local/bin/entrypoint.sh
RUN chmod 755 /usr/local/bin/entrypoint.sh

WORKDIR /var/www/html

ENTRYPOINT ["/usr/local/bin/entrypoint.sh"]
CMD ["php-fpm"]

EXPOSE 9000
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 CMD pgrep -f "php-fpm" > /dev/null || exit 1
