###
### Meta Information
###
FROM localhost/debian

# Build Variables
# uid that the files owner user should have
ARG FILESUID=5000

###
### General Setup
###

# install packages we want
RUN apt update -y && apt install -y apache2 php-fpm php-gd php-zip \
    php-pgsql php-curl php-mbstring php-intl php-imagick php-xml php-gmp \
    php-json redis php-redis postgresql postgresql-doc php-ldap php-bcmath


# put database variables in /etc/environment so anyone can access them
# also autodetect versions of php and postgres and put them in /etc/environment as well
RUN echo "PSQLV=$(psql -V | cut -d ' ' -f 3 | cut -d '.' -f 1)" >> /etc/environment && \
    echo "PHPV=$(echo $(php -r 'echo PHP_VERSION;') | cut -d '.' -f 1-2)" >> /etc/environment

# change www-data's UID to the file owner UID
RUN usermod --uid $FILESUID www-data && \
    groupmod --gid $FILESUID www-data && \
    chown -R www-data:www-data /var/www

# copy our custom scripts
COPY assets/bin/ /usr/local/bin/

###
### PHP
###

# enable PHP interpreter
RUN systemctl enable php${PHPV:?}-fpm

# copy php configuration
COPY assets/php/ php/
RUN mv php/php.ini /etc/php/${PHPV:?}/fpm/ && \
    mv php/www.conf /etc/php/${PHPV:?}/fpm/pool.d/ && \
    rmdir php

###
### PostgreSQL ###
###

# configure PostgreSQL access
COPY --chown=postgres:postgres assets/pg_hba.conf ./
RUN mv pg_hba.conf /etc/postgresql/${PSQLV:?}/main/

###
### Apache
###

# enable modules we need, disable default site
RUN a2enmod rewrite headers env dir mime proxy_fcgi && \
    a2enconf php${PHPV:?}-fpm && \
    a2dissite 000-default

###
### Redis
###

# copy redis config
COPY --chown=redis:redis assets/redis.conf /etc/redis/redis.conf

# add www-data to redis group so it can use the socket
RUN usermod -a -G redis www-data

###
### Bugfix
###

# push the fixed systemd file for redis
COPY assets/bugfix/redis-server.service /etc/systemd/system/redis-server.service

COPY assets/bugfix/apache2.override /etc/systemd/system/apache2.service.d/override.conf

# bugfix for cron
COPY assets/bugfix/cronfix /root/
RUN chmod +x /root/cronfix && /root/cronfix