FROM 086679231553.dkr.ecr.us-east-1.amazonaws.com/docker-parent-images:debian-php82 AS base

USER root

RUN apt-get update && apt-get -y upgrade

# Install and configure apache, php packages
RUN apt-get -y install curl git unzip zip \
    && apt-get clean all \
    && rm -rf /var/lib/apt/lists/*

# Install the DataDog PHP tracer
RUN curl -LO https://github.com/DataDog/dd-trace-php/releases/download/0.96.0/datadog-php-tracer_0.96.0_amd64.deb
RUN dpkg -i datadog-php-tracer_0.96.0_amd64.deb

# Set and prepare the app directory
ENV APP_HOME /var/www/html
RUN chown -R worker $APP_HOME


USER worker

# Copy requirements metadata
COPY composer.json $APP_HOME

WORKDIR $APP_HOME

# Install app and dependencies
RUN mkdir ~/.ssh && ssh-keyscan github.com >> ~/.ssh/known_hosts
RUN --mount=type=secret,id=COMPOSER_AUTH,required=true,uid=1010 COMPOSER_AUTH=$(cat /run/secrets/COMPOSER_AUTH) composer install --no-dev --no-autoloader
RUN composer dump-autoload --optimize

FROM base AS app

USER root

RUN apt-get -y remove --purge git \
    && apt-get -y autoremove

# Install and configure apache, php packages
RUN apt-get -y install apache2 \
    && apt-get clean all \
    && rm -rf /var/lib/apt/lists/*

# Create the cache directory and set permissions
RUN mkdir -p /var/www/html/storage/cache \
    && chown -R www-data:www-data /var/www/html/storage

# Copy app source code
COPY resources $APP_HOME/resources
COPY spec $APP_HOME/spec
COPY src $APP_HOME/src
COPY web $APP_HOME/web
COPY app.php $APP_HOME/

RUN chgrp -R www-data $APP_HOME

# Remove old and add new apache configs
RUN rm -rf /etc/apache2/apache2.conf
COPY deploy/apache2.conf /etc/apache2/apache2.conf

STOPSIGNAL SIGWINCH
EXPOSE 80

COPY deploy/entry_point.sh /usr/local/bin/entry_point.sh
RUN chmod 755 /usr/local/bin/entry_point.sh

ENTRYPOINT  ["/usr/local/bin/entry_point.sh"]


FROM base AS test

USER root

# Install dependencies for running tests
RUN apt-get update && apt-get -y install ant yamllint phpunit

RUN pecl install pcov

# Add pcov configuration to php.ini
RUN echo "extension=pcov.so" >> /etc/php/8.2/cli/php.ini
RUN echo "pcov.enabled=1" >> /etc/php/8.2/cli/php.ini

USER worker
RUN composer install --dev


# Copy app source code and tests
COPY resources $APP_HOME/resources
COPY spec $APP_HOME/spec
COPY src $APP_HOME/src
COPY tests $APP_HOME/tests

COPY composer.json $APP_HOME
copy app.php $APP_HOME/

WORKDIR $APP_HOME

# Install dev dependencies for testing
RUN --mount=type=secret,id=COMPOSER_AUTH,required=true,uid=1010 COMPOSER_AUTH=$(cat /run/secrets/COMPOSER_AUTH) composer install --dev
# autoloader
RUN composer dump-autoload


COPY build/build.xml lint-and-test.sh $APP_HOME/
COPY tests $APP_HOME/tests
COPY docker-compose.yml $APP_HOME/docker-compose.yml

ENTRYPOINT [ "/var/www/html/lint-and-test.sh" ]
