FROM debian:bullseye-slim

# Installation des dépendances de base
RUN apt-get update && apt-get install -y \
    apache2 \
    supervisor \
    wget \
    curl \
    unzip \
    gnupg \
    lsb-release \
    openjdk-17-jdk \
    && rm -rf /var/lib/apt/lists/*

# Installation de Tomcat 10
RUN cd /opt && \
    wget https://archive.apache.org/dist/tomcat/tomcat-10/v10.1.47/bin/apache-tomcat-10.1.47.tar.gz && \
    tar -xzf apache-tomcat-10.1.47.tar.gz && \
    mv apache-tomcat-10.1.47 tomcat && \
    rm apache-tomcat-10.1.47.tar.gz && \
    chmod +x /opt/tomcat/bin/*.sh

# Variables d'environnement Tomcat
ENV CATALINA_HOME=/opt/tomcat
ENV JAVA_HOME=/usr/lib/jvm/java-17-openjdk-amd64
ENV PATH=$PATH:$CATALINA_HOME/bin

# Installation Apache Exporter
RUN wget https://github.com/Lusitaniae/apache_exporter/releases/download/v1.0.10/apache_exporter-1.0.10.linux-amd64.tar.gz \
    && tar xzf apache_exporter-1.0.10.linux-amd64.tar.gz \
    && mv apache_exporter-1.0.10.linux-amd64/apache_exporter /usr/local/bin/ \
    && rm -rf apache_exporter-*

# Installation Node Exporter
RUN wget https://github.com/prometheus/node_exporter/releases/download/v1.7.0/node_exporter-1.7.0.linux-amd64.tar.gz \
    && tar xzf node_exporter-1.7.0.linux-amd64.tar.gz \
    && mv node_exporter-1.7.0.linux-amd64/node_exporter /usr/local/bin/ \
    && rm -rf node_exporter-*

# Installation Promtail
RUN wget https://github.com/grafana/loki/releases/download/v2.9.0/promtail-linux-amd64.zip \
    && unzip promtail-linux-amd64.zip \
    && mv promtail-linux-amd64 /usr/local/bin/promtail \
    && chmod +x /usr/local/bin/promtail \
    && rm promtail-linux-amd64.zip

# Copie des configurations
COPY configs/apache/httpd.conf /etc/apache2/sites-available/000-default.conf
COPY configs/promtail/config.yaml /etc/promtail/config.yaml
COPY configs/supervisord/supervisord.conf /etc/supervisor/conf.d/supervisord.conf

# Configuration Apache pour server-status
RUN echo '<Location "/server-status">\n\
    SetHandler server-status\n\
    Require all granted\n\
</Location>' > /etc/apache2/conf-available/server-status.conf \
    && a2enconf server-status \
    && a2enmod status \
    && a2enmod proxy \
    && a2enmod proxy_http

# Configuration du proxy Apache vers Tomcat
RUN echo '<VirtualHost *:80>\n\
    ProxyPreserveHost On\n\
    ProxyPass /api http://localhost:8080/api\n\
    ProxyPassReverse /api http://localhost:8080/api\n\
</VirtualHost>' > /etc/apache2/sites-available/000-default.conf

# Création des répertoires de logs
RUN mkdir -p /var/log/apache2 /var/log/promtail /opt/tomcat/logs

# Copie du WAR (à placer dans le contexte de build)
COPY archiweb-api-1.0.0.war /opt/tomcat/webapps/api.war

EXPOSE 80 8080 9100 9117 9080

CMD ["/usr/bin/supervisord", "-c", "/etc/supervisor/conf.d/supervisord.conf"]
