ARG PARENT_IMAGE=086679231553.dkr.ecr.us-east-1.amazonaws.com/docker-parent-images:debian-php82
FROM $PARENT_IMAGE AS parent

# Set user
USER root

# Clean package cache and update
RUN apt-get update && \
    apt-get -y upgrade

# Install and configure apache and php packages
RUN apt-get -y install git apache2 unzip zip cron

# Clean up after installation
RUN apt-get clean && rm -rf /var/lib/apt/lists/*

# # Set Datadog params
# ENV DD_TRACE_ANALYTICS_ENABLED true
# ENV DD_TRACE_APP_NAME prs-toolkit
# ENV DD_TRACE_DEBUG false
# ENV DD_TRACE_GLOBAL_TAGS env:prs-toolkit

# Set and prepare the app directory
ENV APP_HOME /var/www/html/prs

# Set the working directory
WORKDIR ${APP_HOME}

# Copy the app into the image
COPY ./ $APP_HOME
RUN <<EOF
rm -rf $APP_HOME/.git
rm -rf $APP_HOME/deploy
rm -rf $APP_HOME/.DS_Store *.shadow
rm -rf $APP_HOME/tests
EOF

# Set group permissions for the app directory
RUN chgrp -R www-data ${APP_HOME}

# Custom php.ini directives (adjust path to match Debian's PHP config location)
COPY --chown=root:root ./deploy/custom_php.ini /etc/php/8.2/mods-available/custom_php.ini
RUN phpenmod custom_php

# Create symlink for the output and uploads folder for AWS EFS under $APP_HOME
RUN <<EOF
ln -s /mnt/prs/output/ /var/www/html/prs/
ln -s /mnt/prs/uploads/ /var/www/html/prs/royalty_assistant_DB/
mkdir -p /mnt/prs/output
mkdir -p /mnt/prs/uploads
chown -R www-data:www-data /mnt/prs/output
chown -R www-data:www-data /mnt/prs/uploads
chown -R www-data:www-data /var/www/html/prs/output
chown -R www-data:www-data /var/www/html/prs/royalty_assistant_DB/uploads
chown -R www-data:www-data /tmp
EOF

# Deploy entrypoint script
COPY deploy/entry_point.sh /usr/local/bin/entry_point.sh
RUN chmod +x /usr/local/bin/entry_point.sh

# Deploy crontab
COPY deploy/crontab /tmp/prs-cron
RUN crontab /tmp/prs-cron && rm -f /tmp/prs-cron

# Remove old and add new apache configs
RUN rm -rf \
  /etc/apache2/mods-enabled \
  /etc/apache2/sites-enabled/default-ssl.conf \
  /etc/apache2/sites-enabled/000-default.conf \
  /etc/apache2/apache2.conf \
  /var/www/html/index.html

# Copy apache config
COPY deploy/apache2.conf /etc/apache2/apache2.conf

# Install app and dependencies
ENV COMPOSER_ALLOW_SUPERUSER=1
RUN composer install --no-dev && composer dump-autoload --optimize

# Clean up after installation
RUN apt-get -y autoremove git && apt-get clean && rm -rf /var/lib/apt/lists/*

STOPSIGNAL SIGWINCH
EXPOSE 80

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