FROM ruby:2.7.1-alpine as Builder

RUN apk add --update --no-cache build-base nodejs yarn mariadb-dev tzdata imagemagick nano

WORKDIR /home/rails/app

COPY Gemfile* ./
RUN bundle config --global frozen 1 \
 && bundle install --without development test \
 && rm -rf /usr/local/bundle/cache/*.gem \
 && find /usr/local/bundle/gems/ -name "*.c" -delete \
 && find /usr/local/bundle/gems/ -name "*.o" -delete

COPY package.json yarn.lock ./
RUN yarn install

COPY . .

RUN RAILS_ENV=production bundle exec rails assets:precompile
RUN rm -rf node_modules tmp/cache

FROM ruby:2.6.6-alpine

# Add Alpine packages
RUN apk add --update --no-cache mariadb-dev imagemagick tzdata

RUN adduser rails --gecos "" --disabled-password
USER rails

COPY --from=Builder /usr/local/bundle/ /usr/local/bundle/
COPY --from=Builder --chown=1000:1000 /home/rails/app /home/rails/app

WORKDIR /home/rails/app
ENV RAILS_ENV=production
COPY entrypoint.sh /entrypoint.sh
ENTRYPOINT ["/entrypoint.sh"]