{%- if hf_cache %}
{%- include "cache.Dockerfile.jinja" %}
{%- endif %}

{% extends "base.Dockerfile.jinja" %}

{% block base_image_patch %}
# If user base image is supplied in config, apply build commands from truss base image
{% if config.base_image %}
ENV PYTHONUNBUFFERED True
ENV DEBIAN_FRONTEND=noninteractive

RUN apt update && \
    apt install -y bash \
                build-essential \
                git \
                curl \
                ca-certificates \
                software-properties-common \
    && apt-get autoremove -y \
    && apt-get clean -y \
    && rm -rf /var/lib/apt/lists/*

COPY ./base_server_requirements.txt base_server_requirements.txt
RUN pip install -r base_server_requirements.txt --no-cache-dir && rm -rf /root/.cache/pip

    {%- if config.live_reload %}
RUN $PYTHON_EXECUTABLE -m venv -h >/dev/null \
    || { pythonVersion=$(echo $($PYTHON_EXECUTABLE --version) | cut -d" " -f2 | cut -d"." -f1,2) \
    && add-apt-repository -y ppa:deadsnakes/ppa \
    && apt update -y && apt install -y --no-install-recommends python$pythonVersion-venv \
    && apt-get autoremove -y \
    && apt-get clean -y \
    && rm -rf /var/lib/apt/lists/*; }
# Create symlink for control server to start inference server process with correct python executable
RUN readlink {{config.base_image.python_executable_path}} &>/dev/null \
    && echo "WARNING: Overwriting existing link at /usr/local/bin/python"
RUN ln -sf {{config.base_image.python_executable_path}} /usr/local/bin/python
    {%- endif %}
{% endif %}

{% endblock %}

{% block install_requirements %}
    {%- if should_install_server_requirements %}
COPY ./server_requirements.txt server_requirements.txt
RUN pip install -r server_requirements.txt --no-cache-dir && rm -rf /root/.cache/pip
    {%- endif %}
{{ super() }}
{% endblock %}


{% block app_copy %}
# Copy data before code for better caching
{%- if data_dir_exists %}
COPY ./{{config.data_dir}} /app/data
{%- endif %}

COPY ./server /app
COPY ./{{ config.model_module_dir }} /app/model
COPY ./config.yaml /app/config.yaml
    {%- if config.live_reload %}
COPY ./control /control
RUN python3 -m venv /control/.env \
    && /control/.env/bin/pip3 install -r /control/requirements.txt
    {%- endif %}

{%- if hf_cache %}
    {%- set hf_dst_directory="/root/.cache/huggingface/hub/"%}
    {%- include "copy_cache_files.Dockerfile.jinja"%}
{%- endif %}


{% endblock %}

{% block run %}
    {%- if config.live_reload %}
ENV HASH_TRUSS {{truss_hash}}
ENV CONTROL_SERVER_PORT 8080
ENV INFERENCE_SERVER_PORT 8090
ENV SERVER_START_CMD="/control/.env/bin/python3 /control/control/server.py"
ENTRYPOINT ["/control/.env/bin/python3", "/control/control/server.py"]
    {%- else %}
ENV INFERENCE_SERVER_PORT 8080
ENV SERVER_START_CMD="{{(config.base_image.python_executable_path or "python3") ~ " /app/inference_server.py"}}"
ENTRYPOINT ["{{config.base_image.python_executable_path or "python3"}}", "/app/inference_server.py"]
    {%- endif %}
{% endblock %}
