FROM redmine:5-bullseye

COPY plugins/ plugins/
COPY patches/* ./
COPY pre-entrypoint.sh  /

ENV REDMINE_SEND_REMINDERS_DAYS=0 \
	REDMINE_SEND_REMINDERS_CRON_EXPR="0 7 * * 1-5"

RUN set -eux; \
	apt-get update; \
	apt-get install -y --no-install-recommends cron nodejs; \
	savedAptMark="$(apt-mark showmanual)"; \
	apt-get install -y --no-install-recommends gcc make; \
	# Compile FFI module
	chmod 770 /usr/local/bundle/gems /usr/local/bundle/extensions/x86_64-linux /usr/local/bundle/extensions/x86_64-linux/3.1.0; \
	# Remove default cron mess
	rm -f /etc/cron.daily/*; \
	rm -f /etc/cron.d/*; \
	# Install plugin dependencies
	bundle check || bundle install; \
	#   For hourglass plugin
	#   	fill up "database.yml" with bogus entries so the plugin can compile it assets
	echo "production:" >> ./config/database.yml; \
	echo "  adapter: mysql2" >> ./config/database.yml; \
	mv plugins/000_redmine_x_ux_upgrade/init.rb plugins/000_redmine_x_ux_upgrade/init.rb.orig; \
	# WARNING: the next command makes the image larger by almost 100 MB
	echo Hourglass::Assets.compile|rails console; \
	rm ./config/database.yml; \
	mv plugins/000_redmine_x_ux_upgrade/init.rb.orig plugins/000_redmine_x_ux_upgrade/init.rb; \
	# end hourglass plugin
	chmod +x /pre-entrypoint.sh; \
	# setting ENTRYPOINT destroys CMD so replace the entrypoint script and call it later
	# (see bottom note in https://docs.docker.com/engine/reference/builder/#entrypoint)
	mv /docker-entrypoint.sh /orig-entrypoint.sh; \
	mv /pre-entrypoint.sh /docker-entrypoint.sh; \
	# Apply patches
	git apply project_identifier.patch; \
	rm *.patch; \
	# Clean-up
	apt-mark auto '.*' > /dev/null; \
	[ -z "$savedAptMark" ] || apt-mark manual $savedAptMark; \
	find /usr/local -type f -executable -exec ldd '{}' ';' \
		| awk '/=>/ { print $(NF-1) }' \
		| sort -u \
		| grep -v '^/usr/local/' \
		| xargs -r dpkg-query --search \
		| cut -d: -f1 \
		| sort -u \
		| xargs -r apt-mark manual \
	; \
	apt-get purge -y --auto-remove -o APT::AutoRemove::RecommendsImportant=false; \
	apt-get clean; \
	rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/* ~/.cache;
