FROM alpine:3.7
MAINTAINER Disassembler <disassembler@dasm.cz>

RUN \
 # Install NodeJS runtime
 apk --no-cache add nodejs paxctl \
 # Fix grsec attributes to loosen memory protection restrictions
 && paxctl -cm /usr/bin/node \
 # Cleanup
 && apk del paxctl

RUN \
 # Install Ruby runtime dependencies
 apk --no-cache add gdbm libressl readline zlib

RUN \
 # Install Ruby build dependencies
 apk --no-cache add --virtual .deps build-base autoconf gdbm-dev libressl-dev linux-headers readline-dev zlib-dev \
 # Download and unpack Ruby
 && wget http://cache.ruby-lang.org/pub/ruby/2.3/ruby-2.3.6.tar.xz -O ruby.tar.xz \
 && mkdir -p /usr/src/ruby \
 && tar -xJf ruby.tar.xz -C /usr/src/ruby --strip-components=1 \
 && rm ruby.tar.xz \
 && cd /usr/src/ruby \
 # Hackfix to suppress "Insecure world writable dir" warning
 && sed -ni 'p;13a #define ENABLE_PATH_CHECK 0' file.c \
 # Configure compilation + hackfix to detect isnan/isinf macros
 && autoconf \
 && ac_cv_func_isnan=yes ac_cv_func_isinf=yes ./configure --build=x86_64-linux-musl --disable-install-doc --enable-shared \
 # Compile and install Ruby
 && make -j $(nproc) \
 && make install \
 # Install RubyGems and Bundler
 && mkdir -p /usr/local/etc \
 && echo -e 'install: --no-document\nupdate: --no-document' >/usr/local/etc/gemrc \
 && gem update --system \
 # Cleanup
 && cd /tmp \
 && rm -r /usr/src/ruby \
 && apk del .deps \
 && rm -rf /root/.gem

ENV RAILS_ENV production

RUN \
 # Install runtime dependencies
 apk --no-cache add libpq libxml2 libxslt tzdata

RUN \
 # Install build dependencies
 apk --no-cache add --virtual .deps build-base git libxml2-dev libxslt-dev linux-headers postgresql-dev yarn zlib-dev \
 # Clone CrisisCleanup
 && git clone --depth 1 https://github.com/CrisisCleanup/crisiscleanup /srv/crisiscleanup \
 # Hackfix ruby dependency versions
 && sed -i 's/2\.2\.5/2.3.6/' /srv/crisiscleanup/Gemfile \
 && sed -i 's/rdoc (4\.2\.0)/rdoc (4.3.0)/' /srv/crisiscleanup/Gemfile.lock \
 # Install Ruby and NodeJS dependencies
 && cd /srv/crisiscleanup \
 && bundle config build.nokogiri --use-system-libraries \
 && bundle install \
 && npm install \
 && yarn \
 # Create CrisisCleanup secret
 && echo -e "production:\n  secret_key_base: $(rake secret)" >/srv/crisiscleanup/config/secrets.yml \
 # Generate static resources
 && rake assets:precompile \
 # Create OS user
 && addgroup -S -g 8005 crisiscleanup \
 && adduser -S -u 8005 -h /srv/crisiscleanup -s /bin/false -g crisiscleanup -G crisiscleanup crisiscleanup \
 && chown -R crisiscleanup:crisiscleanup /srv/crisiscleanup \
 # Cleanup
 && apk del .deps \
 && find /srv/crisiscleanup -name '.git*' -exec rm -rf {} + \
 && rm -rf /usr/local/share/.cache \
 && rm -rf /root/.bundle /root/.config /root/.npm

VOLUME ["/srv/crisiscleanup/config"]
EXPOSE 8005

USER crisiscleanup
WORKDIR /srv/crisiscleanup
CMD ["rails", "server"]