---
# Datei: ansible/playbooks/deploy/includes/docker_setup.yml
# Verwaltet die Docker-Umgebung und Grundkonfigurationen

- name: Stelle sicher, dass die Docker-Verzeichnisstruktur existiert
  file:
    path: "{{ docker_compose_project_path }}/{{ item }}"
    state: directory
    mode: '0755'
    recurse: yes
  loop:
    - "docker/php"
    - "docker/nginx"
    - "docker/redis"
    - "src"
    - "public"
    - "cache"

- name: Docker-Basis-Konfiguration erstellen für PHP
  copy:
    dest: "{{ docker_compose_project_path }}/docker/php/Dockerfile-simple"
    content: |
      FROM php:8.4-fpm

      RUN apt-get update && apt-get install -y \
          git \
          unzip \
          libzip-dev \
          zip \
          && docker-php-ext-install zip pdo pdo_mysql \
          && docker-php-ext-install opcache \
          && docker-php-ext-install pcntl posix shmop \
          && apt-get clean \
          && rm -rf /var/lib/apt/lists/*

      WORKDIR /var/www/html

      # Kein Composer-Befehl hier

      CMD ["php-fpm"]
    owner: root
    group: root
    mode: '0644'

- name: Erstelle Nginx-Konfiguration
  copy:
    dest: "{{ docker_compose_project_path }}/docker/nginx/nginx.conf"
    content: |
      user  nginx;
      worker_processes  auto;

      error_log  /var/log/nginx/error.log warn;
      pid        /var/run/nginx.pid;

      events {
          worker_connections  1024;
      }

      http {
          include       /etc/nginx/mime.types;
          default_type  application/octet-stream;

          log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                            '$status $body_bytes_sent "$http_referer" '
                            '"$http_user_agent" "$http_x_forwarded_for"';

          access_log  /var/log/nginx/access.log  main;

          sendfile        on;
          keepalive_timeout  65;

          include /etc/nginx/conf.d/*.conf;
      }
    mode: '0644'

- name: Erstelle Nginx Default-Site-Konfiguration
  copy:
    dest: "{{ docker_compose_project_path }}/docker/nginx/default.conf"
    content: |
      server {
          listen 80;
          listen [::]:80;
          server_name _;

          root /var/www/html/public;
          index index.php index.html;

          location / {
              try_files $uri $uri/ /index.php?$query_string;
          }

          location ~ \.php$ {
              fastcgi_pass php:9000;
              fastcgi_index index.php;
              fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
              include fastcgi_params;
          }
      }
    mode: '0644'

- name: Erstelle Redis-Konfiguration (falls benötigt)
  copy:
    dest: "{{ docker_compose_project_path }}/docker/redis/redis.conf"
    content: |
      # Redis Konfiguration
      maxmemory 256mb
      maxmemory-policy allkeys-lru
    mode: '0644'
  when: false  # Nur aktivieren, wenn Redis-Konfiguration benötigt wird
