---
- name: Stelle sicher, dass Nginx-Verzeichnisse existieren
  ansible.builtin.file:
    path: "{{ nginx_target_dir }}"
    state: directory
    recurse: yes
    mode: '0755'

- name: Kopiere Nginx-Konfigurationsdateien
  ansible.builtin.copy:
    src: "{{ playbook_dir }}/../docker/nginx/{{ item }}"
    dest: "{{ nginx_target_dir }}/{{ item }}"
    mode: '0644'
  loop:
    - nginx.conf
    - default.conf
  notify: reload nginx

- name: Erstelle nginx.conf
  ansible.builtin.copy:
    dest: "{{ nginx_target_dir }}/nginx.conf"
    content: |
      user  nginx;
      worker_processes  {{ nginx_worker_processes }};

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

      events {
          worker_connections  {{ nginx_worker_connections }};
      }

      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: Überprüfe ob default.conf ein Verzeichnis ist
  stat:
    path: "{{ nginx_target_dir }}/default.conf"
  register: default_conf_stat

- name: Entferne default.conf Verzeichnis falls es existiert
  file:
    path: "{{ nginx_target_dir }}/default.conf"
    state: absent
  when: default_conf_stat.stat.exists and default_conf_stat.stat.isdir

- name: Erstelle default.conf
  ansible.builtin.copy:
    dest: "{{ nginx_target_dir }}/default.conf"
    content: |
      server {
          listen 80;
          listen [::]:80;
          server_name {{ app_domain }};

          # Weiterleitung auf HTTPS, wenn verfügbar
          # location / {
          #     return 301 https://$host$request_uri;
          # }

          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;
          }

          # Vite Dev Server Proxy (deaktiviert)
          # include /etc/nginx/vite-proxy.inc;
      }

      # HTTPS Server
      server {
          listen 443 ssl;
          listen [::]:443 ssl;
          server_name {{ app_domain }};

          ssl_certificate     /etc/nginx/ssl/fullchain.pem;
          ssl_certificate_key /etc/nginx/ssl/privkey.pem;
          ssl_protocols       TLSv1.2 TLSv1.3;
          ssl_ciphers         HIGH:!aNULL:!MD5;

          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;
          }

          # Vite Dev Server Proxy (deaktiviert)
          # include /etc/nginx/vite-proxy.inc;
      }
    mode: '0644'

- name: Prüfe ob vite-proxy.inc existiert
  stat:
    path: "{{ nginx_vite_proxy_src }}"
  register: vite_proxy_exists
  delegate_to: localhost
  become: false
---
# Tasks für Nginx-Konfiguration

- name: Nginx-Konfigurationsverzeichnis erstellen
  file:
    path: "{{ deploy_root }}/docker/nginx"
    state: directory
    owner: "{{ deploy_user }}"
    group: "{{ deploy_user }}"
    mode: '0755'

- name: Erstelle Nginx-Hauptkonfiguration
  copy:
    dest: "{{ deploy_root }}/docker/nginx/nginx.conf"
    content: |
      user  nginx;
      worker_processes  {{ nginx_worker_processes }};

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

      events {
          worker_connections  {{ nginx_worker_connections }};
      }

      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;
          #tcp_nopush     on;

          keepalive_timeout  65;

          #gzip  on;

          include /etc/nginx/conf.d/*.conf;
      }
    owner: "{{ deploy_user }}"
    group: "{{ deploy_user }}"
    mode: '0644'
  notify: reload nginx

- name: Erstelle Nginx-Default-Konfiguration
  copy:
    dest: "{{ deploy_root }}/docker/nginx/default.conf"
    content: |
      server {
          listen 80;
          server_name {{ app_domain }} localhost;
          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;
          }

          location ~ /\.ht {
              deny all;
          }
      }
    owner: "{{ deploy_user }}"
    group: "{{ deploy_user }}"
    mode: '0644'
  notify: reload nginx
- name: Kopiere richtige vite-proxy.inc je nach Umgebung (falls vorhanden)
  ansible.builtin.copy:
    src: "{{ nginx_vite_proxy_src }}"
    dest: "{{ nginx_target_dir }}/vite-proxy.inc"
    mode: '0644'
  notify: reload nginx
  when: vite_proxy_exists.stat.exists

- name: Überprüfe ob vite-proxy.inc ein Verzeichnis ist
  stat:
    path: "{{ nginx_target_dir }}/vite-proxy.inc"
  register: vite_proxy_stat

- name: Entferne vite-proxy.inc Verzeichnis falls es existiert
  file:
    path: "{{ nginx_target_dir }}/vite-proxy.inc"
    state: absent
  when: vite_proxy_stat.stat.exists and vite_proxy_stat.stat.isdir

- name: Erstelle Standard vite-proxy.inc Datei (falls nicht vorhanden)
  ansible.builtin.copy:
    dest: "{{ nginx_target_dir }}/vite-proxy.inc"
    content: |
      # Standard Vite Proxy Konfiguration
      location /@vite/ {
          proxy_pass http://localhost:5173/;
          proxy_set_header Host $host;
      }

      location /@fs/ {
          proxy_pass http://localhost:5173/;
          proxy_set_header Host $host;
      }

      location /node_modules/ {
          proxy_pass http://localhost:5173/node_modules/;
          proxy_set_header Host $host;
      }
    mode: '0644'
  notify: reload nginx
  when: not vite_proxy_exists.stat.exists

- name: Überprüfe ob docker-entrypoint.sh ein Verzeichnis ist
  stat:
    path: "{{ nginx_target_dir }}/docker-entrypoint.sh"
  register: entrypoint_stat

- name: Entferne docker-entrypoint.sh Verzeichnis falls es existiert
  file:
    path: "{{ nginx_target_dir }}/docker-entrypoint.sh"
    state: absent
  when: entrypoint_stat.stat.exists and entrypoint_stat.stat.isdir

- name: Erstelle docker-entrypoint Skript
  ansible.builtin.copy:
    dest: "{{ nginx_target_dir }}/docker-entrypoint.sh"
    content: |
      #!/bin/sh

      # Überprüfe SSL-Zertifikate und erstelle selbstsignierte, wenn keine vorhanden sind
      if [ ! -f /etc/nginx/ssl/fullchain.pem ] || [ ! -f /etc/nginx/ssl/privkey.pem ]; then
          echo "Keine SSL-Zertifikate gefunden, erstelle selbstsignierte Zertifikate..."
          mkdir -p /etc/nginx/ssl
          openssl req -x509 -nodes -days 365 -newkey rsa:2048 \
              -keyout /etc/nginx/ssl/privkey.pem \
              -out /etc/nginx/ssl/fullchain.pem \
              -subj "/CN=localhost"
      fi

      # Starte Nginx im Vordergrund
      echo "Starte Nginx..."
      exec nginx -g 'daemon off;'
    mode: '0755'

- name: Baue und starte Nginx-Container (optional, wenn Compose separat genutzt wird, dann hier nicht nötig)
  ansible.builtin.shell: |
    export DOCKER_BUILDKIT=0
    docker-compose -f "{{ deploy_root }}/docker-compose-simple.yml" up -d --build nginx
  args:
    chdir: "{{ deploy_root }}"
    executable: /bin/bash
  when: nginx_target_dir is defined and deploy_root is defined
  register: nginx_compose_result
  ignore_errors: true
  environment:
    COMPOSE_IGNORE_ORPHANS: "True"
    PATH: "/usr/local/bin:/usr/bin:/bin"

- name: Zeige Compose-Resultat
  ansible.builtin.debug:
    var: nginx_compose_result.stdout_lines
  when: nginx_compose_result is defined
