FROM ubuntu:24.04

ENV PYTHONDONTWRITEBYTECODE=1 \
    PYTHONUNBUFFERED=1 \
    PIP_NO_CACHE_DIR=1 \
    DEBIAN_FRONTEND=noninteractive \
    FLASK_HOST=0.0.0.0 \
    FLASK_PORT=6050 \
    FLASK_DEBUG=false \
    APP_DATA_DIR=/app/data \
    SOCKETIO_ASYNC_MODE=threading \
    PATH="/opt/venv/bin:/opt/dell/srvadmin/sbin:${PATH}"

ARG IDRAC_TOOLS_UBUNTU_VERSION=UBUNTU24

WORKDIR /app

RUN apt-get update \
    && apt-get install -y --no-install-recommends \
        bash \
        ca-certificates \
        libargtable2-0 \
        libssl3t64 \
        lsb-base \
        openssl \
        pciutils \
        python3 \
        python3-pip \
        python3-venv \
    && rm -rf /var/lib/apt/lists/*

COPY iDRACTools /tmp/iDRACTools

# Dell iDRAC Tools packages try to start HAPI with systemctl during postinst.
# The image only needs remote racadm/ipmitool, so a build-time shim is enough.
RUN printf '#!/bin/sh\nexit 0\n' > /usr/bin/systemctl \
    && chmod +x /usr/bin/systemctl

RUN apt-get update \
    && apt-get install -y --no-install-recommends \
        /tmp/iDRACTools/racadm/${IDRAC_TOOLS_UBUNTU_VERSION}/x86_64/srvadmin-hapi_*.deb \
        /tmp/iDRACTools/racadm/${IDRAC_TOOLS_UBUNTU_VERSION}/x86_64/srvadmin-idracadm7_*.deb \
        /tmp/iDRACTools/racadm/${IDRAC_TOOLS_UBUNTU_VERSION}/x86_64/srvadmin-idracadm8_*.deb \
        /tmp/iDRACTools/ipmitool/${IDRAC_TOOLS_UBUNTU_VERSION}_x86_64/ipmitool_*.deb \
    && rm -f /usr/bin/systemctl \
    && rm -rf /tmp/iDRACTools /var/lib/apt/lists/*

RUN python3 -m venv /opt/venv

COPY requirements.txt .
RUN pip install --upgrade pip \
    && pip install -r requirements.txt

COPY app.py config.py ./
COPY backend ./backend
COPY migrations ./migrations
COPY data ./data

RUN mkdir -p /app/data /app/backend/instance \
    && find /app/data -type f \( -name "*.sh" -o -name "*.py" \) -exec chmod +x {} \;

EXPOSE 6050

HEALTHCHECK --interval=30s --timeout=5s --start-period=20s --retries=3 \
    CMD python -c "import os, socket; s = socket.create_connection(('127.0.0.1', int(os.getenv('FLASK_PORT', '6050'))), 5); s.close()"

CMD ["python", "app.py"]
