ARG WP_VERSION=6
ARG PHP_VERSION=8.3

FROM wordpress:${WP_VERSION}-php${PHP_VERSION}-fpm-alpine

RUN cp -avf /usr/local/bin/docker-entrypoint.sh /usr/local/bin/docker-entrypoint.original && \
    sed -i '/^[[:space:]]*exec "$@"[[:space:]]*/d' /usr/local/bin/docker-entrypoint.sh && \
    cat << EOF >> /usr/local/bin/docker-entrypoint.sh
# Run entrypoint hooks
SH_PATH=$(which sh);
if [ -d /docker-entrypoint.d ]; then
    for entrypoint in /docker-entrypoint.d/*.sh; do
        order=\$(basename \${entrypoint} | grep -oE '^\d+');
        script_user=\$(test -n "\$(basename \${entrypoint} | grep -oE '\-unpriv\.sh')" && echo \${UNPRIV_USER:-\$(stat -c %U /var/www/html)} || echo "root");
        name=\$(basename \${entrypoint} | sed 's/\.sh//' |  sed 's/\-unpriv//' | sed 's/^\d\+\-//')
        printf "=== %s [#%d] ===\nrunning as '%s'\n\n" \$(echo \${name} | tr [:lower:] [:upper:]) \${order} \${script_user}
        su \${script_user} -s \$(which sh) \$entrypoint;
    done
fi

exec "\$@";
EOF

RUN curl -O https://raw.githubusercontent.com/wp-cli/builds/gh-pages/phar/wp-cli.phar && \
    chmod +x wp-cli.phar && \
    mv wp-cli.phar /usr/local/bin/wp

# Copy sub scripts and allows execution
COPY ./scripts/docker-entrypoint.d/* /docker-entrypoint.d/
RUN chmod +x /docker-entrypoint.d/*.sh