# Dockerfile pour Homelab Automation Dashboard avec Ansible
FROM python:3.11-slim

# Métadonnées
LABEL maintainer="Homelab Automation"
LABEL description="Dashboard d'automatisation Homelab avec FastAPI et Ansible"
LABEL version="1.0"

# Variables d'environnement
ENV PYTHONDONTWRITEBYTECODE=1
ENV PYTHONUNBUFFERED=1
ENV ANSIBLE_HOST_KEY_CHECKING=False
ENV ANSIBLE_RETRY_FILES_ENABLED=False

# Répertoire de travail
WORKDIR /app

# Installation des dépendances système pour Ansible et SSH
RUN apt-get update && apt-get install -y --no-install-recommends \
    openssh-client \
    sshpass \
    ansible \
    ansible-lint \
    git \
    curl \
    libjpeg62-turbo \
    zlib1g \
    libfreetype6 \
    libpng16-16 \
    fonts-noto-color-emoji \
    && rm -rf /var/lib/apt/lists/* \
    && apt-get clean

 ARG TTYD_VERSION=1.7.7
 RUN set -eux; \
     arch="$(dpkg --print-architecture)"; \
     case "$arch" in \
       amd64) ttyd_arch="x86_64" ;; \
       arm64) ttyd_arch="aarch64" ;; \
       *) echo "Unsupported architecture for ttyd: $arch" >&2; exit 1 ;; \
     esac; \
     curl -fsSL -o /usr/local/bin/ttyd "https://github.com/tsl0922/ttyd/releases/download/${TTYD_VERSION}/ttyd.${ttyd_arch}"; \
     chmod +x /usr/local/bin/ttyd

# Création du répertoire SSH et configuration
RUN mkdir -p /root/.ssh && chmod 700 /root/.ssh

# Copie des requirements et installation des dépendances Python
COPY app/requirements.txt ./
RUN pip install --no-cache-dir -r requirements.txt

# Copie du point d'entrée principal
COPY main.py ./

# Copie du code de l'application (doit rester un sous-dossier /app/app/)
COPY app/ ./app/

# Copie de la configuration Ansible
COPY ansible/ /ansible/

# Copie des fichiers Alembic (migrations)
COPY alembic/ /alembic/
COPY alembic.ini /alembic.ini

# Création du répertoire pour les clés SSH (sera monté en volume)
RUN mkdir -p /app/ssh_keys /app/data

# Configuration Ansible pour utiliser le bon répertoire
ENV ANSIBLE_CONFIG=/ansible/ansible.cfg

# Variables par défaut pour la base SQLite dans le conteneur
ENV LOGS_DIR=/app/data
ENV HOMELAB_DATA_DIR=/app/data
ENV DB_PATH=/app/data/homelab.db
ENV DATABASE_URL=sqlite+aiosqlite:////app/data/homelab.db

# Exposition du port
EXPOSE 8008

# Health check
HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \
    CMD curl -f http://localhost:8008/api/health || exit 1

# Commande de démarrage
CMD ["python", "-m", "uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8008"]
