FROM php:8.2-fpm-alpine AS chill_base_php82

ENV POSTGRES_VERSION 14

# default UID for the PHP user
ARG UID=1000
ARG GID=1000

# install php extensions and deps
RUN apk update && apk add --no-cache \
    wget gnupg \
    libpq-dev \
    icu-dev icu-libs icu-data-full \
    oniguruma-dev \
    libzip libzip-dev \
    linux-headers \
    gcc g++ make autoconf \
    bash git \
    && docker-php-ext-install pdo_pgsql intl mbstring zip bcmath exif sockets \
    && git clone https://github.com/nikic/php-ast.git \
    && cd php-ast \
    && phpize \
    && ./configure \
    && make install \
    && echo 'extension=ast.so' > /usr/local/etc/php/php.ini \
    && cd .. && rm -rf php-ast \
    && pecl install redis \
    && docker-php-ext-enable redis \
    && apk add postgresql${POSTGRES_VERSION}-client \
    && apk del --purge wget gnupg libpq-dev icu-dev oniguruma-dev libzip-dev linux-headers gcc g++ make autoconf

RUN { \
    echo ""; \
    echo "memory_limit = 512M"; \
    echo ""; \
    } >> /usr/local/etc/php/conf.d/memory_limit.ini

RUN { \
    echo ""; \
    echo "[Date]"; \
    echo "date.timezone = Europe/Brussels"; \
    echo ""; \
    } >> /usr/local/etc/php/conf.d/date.ini

# temporary fix, while php-cs-fixer has conflict dependencies
# with chill
RUN curl -o /usr/local/bin/php-cs-fixer https://cs.symfony.com/download/php-cs-fixer-v3.phar \
    && chmod +x /usr/local/bin/php-cs-fixer
# to make php-cs-fixer works with php 8.2
ENV PHP_CS_FIXER_IGNORE_ENV=1

COPY --from=composer:2 /usr/bin/composer /usr/bin/composer
ENV COMPOSER_ALLOW_SUPERUSER=1
ENV COMPOSER_MEMORY_LIMIT=-1

# shell bash preference
RUN sed -i " \
    s|root:x:0:0:root:/root:/bin/ash|root:x:0:0:root:/root:/bin/bash|g; \
    s|postgres:x:70:70:PostgreSQL user:/var/lib/postgresql:/bin/sh|postgres:x:70:70:PostgreSQL user:/var/lib/postgresql:/bin/bash|g" \
    /etc/passwd

# chmod on redis.so
RUN chmod 755 -R /usr/local/lib/php/extensions/

WORKDIR /var/www/app

CMD ["php-fpm"]

FROM chill_base_php82 AS chill_php82

# copy directories

COPY ./bin    /var/www/app/bin/.
COPY ./composer.* /var/www/app/
COPY ./config    /var/www/app/config/.
COPY ./migrations /var/www/app/migrations/.
COPY ./public    /var/www/app/public/.
COPY ./src    /var/www/app/src/.
COPY ./templates /var/www/app/templates/.
COPY ./translations /var/www/app/translations/.
COPY ./vendor /var/www/app/vendor/.

COPY ./.env /var/www/app/.env

# import the manifest.json file
COPY ./public/build/manifest.json /var/www/app/public/build/manifest.json

ADD ./entrypoint.sh /.

RUN chmod +x /entrypoint.sh

ENTRYPOINT ["/entrypoint.sh"]

ENV PHP_FPM_USER=www-data \
    PHP_FPM_GROUP=www-data \
    COMPOSER_HOME=/var/www/app/.composer \
    SESSION_LIFETIME=10800

CMD [ "php-fpm" ]