FROM php:7.4-fpm AS base

WORKDIR /var/www/html

# PHP 7.4 uses Debian Bullseye; use its archived package repositories.
# Archived security metadata expires, but package signatures remain verified.
RUN printf '%s\n' \
  'deb https://archive.debian.org/debian bullseye main' \
  'deb [check-valid-until=no] https://archive.debian.org/debian-security bullseye-security main' \
  > /etc/apt/sources.list \
  && rm -rf /var/lib/apt/lists/* \
  && apt-get -o Acquire::Retries=3 update \
  && apt-get install -y --no-install-recommends \
  git \
  pkg-config \
  unzip \
  libonig-dev \
  libzip-dev \
  libpng-dev \
  libjpeg62-turbo-dev \
  libfreetype6-dev \
  && docker-php-ext-configure gd --with-freetype --with-jpeg \
  && docker-php-ext-install -j"$(nproc)" \
  pdo_mysql \
  mbstring \
  bcmath \
  zip \
  exif \
  gd \
  && rm -rf /var/lib/apt/lists/*

COPY --from=composer:2 /usr/bin/composer /usr/local/bin/composer

COPY docker/php/php.ini /usr/local/etc/php/conf.d/app.ini
COPY docker/php/zz-clear-env.conf /usr/local/etc/php-fpm.d/zz-clear-env.conf
COPY docker/php/entrypoint.sh /usr/local/bin/app-entrypoint.sh

# Normalize Windows checkout line endings before executing the script.
RUN sed -i 's/\r$//' /usr/local/bin/app-entrypoint.sh \
  && chmod +x /usr/local/bin/app-entrypoint.sh \
  && usermod -u 1000 www-data && groupmod -g 1000 www-data

ENTRYPOINT ["app-entrypoint.sh"]
CMD ["php-fpm"]

FROM base AS staging

COPY --chown=www-data:www-data . /var/www/html

RUN composer install --no-interaction --prefer-dist --no-dev --optimize-autoloader --no-scripts \
  && mkdir -p \
  storage/logs \
  storage/framework/cache/data \
  storage/framework/views \
  storage/framework/sessions \
  storage/app/public \
  bootstrap/cache \
  && chown -R www-data:www-data storage bootstrap/cache vendor

FROM base AS development
