# Das Basis-Image ist auf einen Digest gepinnt. Ohne den Pin zieht Docker
# bei jedem Build ein neues python:3.12-slim - und der komplette Layer-Cache
# (Scanner-Downloads, Template-Archiv, Trivy-Datenbank) ist dahin. Mit Pin
# bleibt der Build reproduzierbar und schnell.
FROM python:3.12-slim@sha256:4840d514c583a4d3d8cad3940e68dee6f0f6f3635c12fcd0a3d74c21a5b93a54

ENV PYTHONDONTWRITEBYTECODE=1 \
    PYTHONUNBUFFERED=1 \
    PIP_NO_CACHE_DIR=1 \
    PYTHONPATH=/app/backend \
    PINGOGNITO_DATA_DIR=/data \
    PINGOGNITO_HOST=0.0.0.0 \
    PINGOGNITO_PORT=7464 \
    HOME=/home/pingognito \
    TRIVY_CACHE_DIR=/home/pingognito/.cache/trivy

# Gepinnte Versionen der fertigen Scanner. Bei einem Update hier ändern -
# die Prüfsummen verhindern, dass ein manipuliertes Archiv eingeschleust wird.
ARG NUCLEI_VERSION=3.11.1
ARG NUCLEI_SHA256=ea63d4ae232808cd7c6bc00d0142428e231fab59dae01042246097d195835ab6
ARG NUCLEI_ASSET_ID=506379676
ARG GITLEAKS_VERSION=8.30.1
ARG GITLEAKS_SHA256=551f6fc83ea457d62a0d98237cbad105af8d557003051f41f3e7ca7b3f2470eb
ARG GITLEAKS_ASSET_ID=378332058
ARG TRIVY_VERSION=0.76.1
ARG TRIVY_SHA256=c7cbe3137fb8a48a17574bede3dd6beb16742d1e9772929940fc90082c39d9c0
ARG TRIVY_ASSET_ID=662254617

# nodejs/npm liefern den npm-audit-Provider, git wird von SCA-Integrationen genutzt,
# curl/unzip zum Laden der Scanner-Binaries, nmap/iproute2/snmp für Netzwerk- & Geräte-Scans.
RUN apt-get update \
 && apt-get install -y --no-install-recommends \
      ca-certificates git nodejs npm curl unzip nmap iproute2 iputils-ping snmp \
 && rm -rf /var/lib/apt/lists/*

# Der Dienst läuft nicht als root. Der eigene Benutzer braucht HOME für die
# Scanner-Caches (nuclei, trivy, npm, pip) und Schreibrechte auf /data.
RUN useradd --create-home --uid 1000 --shell /usr/sbin/nologin pingognito \
 && mkdir -p /data /data/reports \
 && chown -R pingognito:pingognito /data /home/pingognito

# --- Fertige Scanner als Binaries -------------------------------------
# Jeder Scanner kommt in eine eigene Layer. GitHubs CDN liefert
# gelegentlich 504 - fällt ein Download aus, ist nur diese Layer betroffen.
# Die bereits gelungenen Downloads bleiben im Cache erhalten, der nächste
# Buildversuch macht also dort weiter, wo der letzte aufgegeben hat.
#
# Jeder Download geht zuerst über die Release-URL und dann über den
# Asset-Endpunkt der GitHub-API. Liefert der erste Weg 504, geht der
# zweite oft trotzdem. Beide nennen dieselbe Datei - die Prüfsumme
# entscheidet, ein manipuliertes Archiv fällt also auch hier auf.
RUN set -eux; \
    for url in \
      "https://github.com/projectdiscovery/nuclei/releases/download/v${NUCLEI_VERSION}/nuclei_${NUCLEI_VERSION}_linux_amd64.zip?download=1" \
      "https://api.github.com/repos/projectdiscovery/nuclei/releases/assets/${NUCLEI_ASSET_ID}" ; do \
      curl -fsSL --retry 8 --retry-all-errors --retry-delay 5 \
        -H "Accept: application/octet-stream" -o /tmp/nuclei.zip "$url" && break || true; \
    done; \
    echo "${NUCLEI_SHA256}  /tmp/nuclei.zip" | sha256sum -c -; \
    unzip -q /tmp/nuclei.zip -d /usr/local/bin; \
    rm /tmp/nuclei.zip; \
    chmod +x /usr/local/bin/nuclei; \
    nuclei -version

RUN set -eux; \
    for url in \
      "https://github.com/gitleaks/gitleaks/releases/download/v${GITLEAKS_VERSION}/gitleaks_${GITLEAKS_VERSION}_linux_x64.tar.gz?download=1" \
      "https://api.github.com/repos/gitleaks/gitleaks/releases/assets/${GITLEAKS_ASSET_ID}" ; do \
      curl -fsSL --retry 8 --retry-all-errors --retry-delay 5 \
        -H "Accept: application/octet-stream" -o /tmp/gitleaks.tar.gz "$url" && break || true; \
    done; \
    echo "${GITLEAKS_SHA256}  /tmp/gitleaks.tar.gz" | sha256sum -c -; \
    tar -xzf /tmp/gitleaks.tar.gz -C /usr/local/bin gitleaks; \
    rm /tmp/gitleaks.tar.gz; \
    chmod +x /usr/local/bin/gitleaks; \
    gitleaks version

RUN set -eux; \
    for url in \
      "https://github.com/aquasecurity/trivy/releases/download/v${TRIVY_VERSION}/trivy_${TRIVY_VERSION}_Linux-64bit.tar.gz?download=1" \
      "https://api.github.com/repos/aquasecurity/trivy/releases/assets/${TRIVY_ASSET_ID}" ; do \
      curl -fsSL --retry 8 --retry-all-errors --retry-delay 5 \
        -H "Accept: application/octet-stream" -o /tmp/trivy.tar.gz "$url" && break || true; \
    done; \
    echo "${TRIVY_SHA256}  /tmp/trivy.tar.gz" | sha256sum -c -; \
    tar -xzf /tmp/trivy.tar.gz -C /usr/local/bin trivy; \
    rm /tmp/trivy.tar.gz; \
    chmod +x /usr/local/bin/trivy; \
    trivy --version

# --- Nuclei-Templates vorab laden, damit Scans ohne Internet laufen ---
# nuclei sucht die Templates standardmäßig unter $HOME/nuclei-templates.
RUN mkdir -p /home/pingognito/nuclei-templates \
 && ( curl -fsSL --retry 8 --retry-all-errors --retry-delay 5 --retry-max-time 180 -o /tmp/tpl.zip https://github.com/projectdiscovery/nuclei-templates/archive/refs/heads/main.zip \
      && unzip -q /tmp/tpl.zip -d /tmp/tpl \
      && cp -r /tmp/tpl/nuclei-templates-main/. /home/pingognito/nuclei-templates/ \
      && rm -rf /tmp/tpl /tmp/tpl.zip ) \
 || echo "Hinweis: Nuclei-Templates nicht vorab geladen - nuclei nutzt dann seine eingebauten Templates."

# --- Trivy-Datenbank vorab laden ---
RUN mkdir -p /home/pingognito/.cache/trivy \
 && ( trivy image --download-db-only ) \
 || echo "Hinweis: Trivy-DB nicht vorab geladen - wird beim ersten Scan geholt."

RUN chown -R pingognito:pingognito /home/pingognito

WORKDIR /app

COPY backend/requirements.txt /app/backend/requirements.txt
COPY backend/requirements-optional.txt /app/backend/requirements-optional.txt

RUN pip install --upgrade pip \
 && pip install -r /app/backend/requirements.txt \
 && (pip install -r /app/backend/requirements-optional.txt || echo "optionale Scanner nicht installiert - läuft ohne weiter")

# --- Offline-Übersetzung (EN/DE/CS) ---
# argostranslate läuft rein auf der CPU (CPU-only PyTorch). Die Modelle werden
# beim Build geladen, damit die Übersetzung ohne Internet funktioniert.
# Schlägt das fehl, bleibt die App lauffähig (Katalog + Cache + Online-Fallback).
COPY backend/install_argos_models.py /tmp/install_argos_models.py
RUN (pip install --no-cache-dir --extra-index-url https://download.pytorch.org/whl/cpu argostranslate \
      && python /tmp/install_argos_models.py) \
 || echo "Hinweis: Offline-Übersetzungsmodelle nicht vorab geladen - Katalog/Cache/Online-Fallback bleiben aktiv."
RUN rm -f /tmp/install_argos_models.py \
 && mkdir -p /home/pingognito/.local/share \
 && chown -R pingognito:pingognito /home/pingognito

COPY backend /app/backend
COPY frontend /app/frontend

# Ab hier läuft alles ohne Root-Rechte.
USER pingognito

EXPOSE 7464

HEALTHCHECK --interval=30s --timeout=6s --start-period=15s --retries=3 \
  CMD python -c "import os,sys,urllib.request;p=os.getenv('PINGOGNITO_PORT','7464');sys.exit(0 if urllib.request.urlopen(f'http://127.0.0.1:{p}/api/health',timeout=5).status==200 else 1)"

CMD ["sh", "-c", "exec uvicorn app.main:app --app-dir /app/backend --host \"${PINGOGNITO_HOST:-0.0.0.0}\" --port \"${PINGOGNITO_PORT:-7464}\""]
