FROM 086679231553.dkr.ecr.us-east-1.amazonaws.com/docker-parent-images:python311 as base

ARG CINC_SERVER_VERSION=15.10.91

USER root

# Update packages and install packages required to install Chef Server
RUN apt-get -y update \
    && apt-get -y upgrade \
    && apt-get install -y wget net-tools ethtool iproute2 cron locales \
    && apt-get -y clean \
    && rm -rf /var/lib/apt/lists/*

# Download and install Cinc Server (free distribution of Chef)
RUN wget https://downloads.cinc.sh/files/stable/cinc-server/${CINC_SERVER_VERSION}/debian/13/cinc-server-core_${CINC_SERVER_VERSION}-1_amd64.deb -O cinc-server-core.deb \
    && dpkg -i cinc-server-core.deb \
    && rm cinc-server-core.deb

# Chef Server relies on systemd, so we use docker-systemctl-replacement to mimic systemctl calls
ENV VIRTUAL_ENV /var/venv
RUN python3.11 -m venv ${VIRTUAL_ENV}
ENV PATH "$VIRTUAL_ENV/bin:$PATH"
RUN pip install docker-systemctl-replacement==1.5.8066 awscli
RUN pip install --upgrade setuptools
RUN ln -s /var/venv/bin/systemctl.py /usr/bin/systemctl

# Configure locale
RUN sed -i -e 's/# en_US.UTF-8 UTF-8/en_US.UTF-8 UTF-8/' /etc/locale.gen \
    && dpkg-reconfigure --frontend=noninteractive locales
ENV LANG en_US.UTF-8
ENV LC_ALL en_US.UTF-8

COPY cinc-server.rb /usr/share/chef/cinc-server.rb
COPY entrypoint.sh /

ENTRYPOINT ["/entrypoint.sh"]

# For local dev, we need to do some extra legwork to get things working with x86 emulation on ARM
# The erlang components of Chef Server fail to start with segmentation fault errors on M1s.
# A workaround for this is to set the ERL_FLAGS environment variable, as per https://elixirforum.com/t/apple-silicon-and-cross-platform-docker-fails-minikube/60699/14
# Unfortunately setting this globally doesn't work and Chef doesn't provide a means for specifying this anywhere, so we have to edit the templates directly.
FROM base as dev

RUN sed -i '/export PATH/s/$/; export ERL_FLAGS="+JPperf true"/' /opt/cinc-project/embedded/cookbooks/infra-server/templates/default/sv-oc_bifrost-run.erb
RUN sed -i '/export PATH/s/$/; export ERL_FLAGS="+JPperf true"/' /opt/cinc-project/embedded/cookbooks/infra-server/templates/default/sv-opscode-erchef-run.erb
