---
- name: Vereinfachtes Deployment mit Docker
  hosts: all
  become: true
  gather_facts: true

  vars:
    deploy_root: /var/www/michaelschiemer
    deploy_user: "{{ ansible_user | default('deploy') }}"
    app_domain: "{{ hostvars[inventory_hostname]['ansible_host'] | default(inventory_hostname) }}"

  tasks:
    # 1. Grundlegende Server-Einrichtung
    - name: Installiere grundlegende Pakete
      apt:
        name: [curl, ca-certificates, gnupg, apt-transport-https, software-properties-common, iproute2]
        state: present
        update_cache: yes

    # 2. Docker Installation
    - name: Docker GPG-Schlüssel hinzufügen
      apt_key:
        url: https://download.docker.com/linux/{{ ansible_distribution | lower }}/gpg
        state: present

    - name: Docker Repository hinzufügen
      apt_repository:
        repo: "deb [arch=amd64] https://download.docker.com/linux/{{ ansible_distribution | lower }} {{ ansible_distribution_release }} stable"
        state: present

    - name: Docker Engine installieren
      apt:
        name: [docker-ce, docker-ce-cli, containerd.io, docker-compose-plugin]
        state: present
        update_cache: yes

    - name: Benutzer zur Docker-Gruppe hinzufügen
      user:
        name: "{{ ansible_user }}"
        groups: docker
        append: yes

    - name: Docker-Service aktivieren
      service:
        name: docker
        state: started
        enabled: yes

    # 3. Verzeichnisstruktur anlegen
    - name: Stelle sicher, dass die Verzeichnisse existieren
      file:
        path: "{{ deploy_root }}/{{ item }}"
        state: directory
        mode: '0755'
        owner: "{{ deploy_user }}"
        group: "{{ deploy_user }}"
        recurse: yes
      loop:
        - public
        - docker/nginx
        - docker/php
        - src

    # 4. Docker-Compose Datei erstellen
    - name: Erstelle docker-compose.yml
      copy:
        dest: "{{ deploy_root }}/docker-compose.yml"
        content: |
          version: '3.8'

          services:
            php:
              container_name: michaelschiemer_php
              image: php:8.4-fpm
              volumes:
                - ./src:/var/www/html/src:rw
                - ./public:/var/www/html/public:rw
              networks:
                - backend

            nginx:
              container_name: michaelschiemer_nginx
              image: nginx:alpine
              ports:
                - "80:80"
                - "443:443"
              volumes:
                - ./public:/var/www/html/public:ro
                - ./docker/nginx/nginx.conf:/etc/nginx/nginx.conf:ro
                - ./docker/nginx/default.conf:/etc/nginx/conf.d/default.conf:ro
              depends_on:
                - php
              networks:
                - frontend
                - backend

          networks:
            frontend:
            backend:
        owner: "{{ deploy_user }}"
        group: "{{ deploy_user }}"
        mode: '0644'

    # 5. Nginx Konfiguration erstellen
    - name: Erstelle Nginx-Konfiguration
      copy:
        dest: "{{ deploy_root }}/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: "{{ deploy_root }}/docker/nginx/default.conf"
        content: |
          server {
              listen 80;
              listen [::]:80;
              server_name _;

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

              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'

    # 6. Test HTML-Datei erstellen
    - name: Erstelle Testseite
      copy:
        dest: "{{ deploy_root }}/public/index.html"
        content: |
          <!DOCTYPE html>
          <html>
          <head>
              <title>Webserver ist aktiv</title>
              <style>
                  body { font-family: Arial, sans-serif; margin: 40px; line-height: 1.6; }
                  h1 { color: #333; }
                  .container { max-width: 800px; margin: 0 auto; padding: 20px; border: 1px solid #ddd; border-radius: 5px; }
                  .success { color: green; }
                  .info { margin-top: 20px; background: #f8f8f8; padding: 10px; border-radius: 5px; }
              </style>
          </head>
          <body>
              <div class="container">
                  <h1>Webserver ist <span class="success">aktiv</span>!</h1>
                  <p>Diese Seite bestätigt, dass der Nginx-Webserver korrekt läuft.</p>
                  <div class="info">
                      <h3>Server-Informationen:</h3>
                      <p>Server: {{ inventory_hostname }}</p>
                      <p>IP: {{ ansible_default_ipv4.address }}</p>
                      <p>Deployment-Zeit: {{ ansible_date_time.iso8601 }}</p>
                  </div>
              </div>
          </body>
          </html>
        mode: '0644'

    # 7. Container starten
    - name: Stoppe alle vorhandenen Container
      command: docker-compose down --remove-orphans
      args:
        chdir: "{{ deploy_root }}"
      ignore_errors: yes

    - name: Starte Docker-Container
      command: docker-compose up -d
      args:
        chdir: "{{ deploy_root }}"

    # 8. Status und Tests
    - name: Warte kurz bis Docker-Container gestartet sind
      pause:
        seconds: 5

    - name: Server-IP ermitteln
      shell: hostname -I | awk '{print $1}'
      register: server_ip
      ignore_errors: yes

    - name: Prüfe Nginx-Container Status
      shell: docker ps | grep nginx || echo "Kein Nginx-Container gefunden"
      register: nginx_status
      ignore_errors: yes

    - name: Prüfe ob Port 80 offen ist
      shell: ss -tulpn | grep LISTEN | grep ':80' || echo "Kein Prozess an Port 80 gebunden"
      register: port_80_check
      ignore_errors: yes

    - name: Teste lokalen Zugriff auf Port 80
      shell: curl -s --connect-timeout 5 -I http://localhost:80 || curl -s --connect-timeout 5 -I http://127.0.0.1:80 || echo "Lokale Verbindung fehlgeschlagen"
      register: curl_local_test
      ignore_errors: yes

    - name: Zeige Anwendungsstatus und Server-Informationen
      debug:
        msg: |
          Anwendungsstatus:
          - Server IP: {{ server_ip.stdout | trim | default('nicht verfügbar') }}
          - Domain: {{ app_domain }}

          Docker-Container Status:
          {{ nginx_status.stdout | default('Keine Informationen verfügbar') }}

          Port-Status:
          {{ port_80_check.stdout | default('Keine Port-Informationen verfügbar') }}

          Lokaler Verbindungstest:
          {{ curl_local_test.stdout | default('Keine Testinformationen verfügbar') }}

          Docker-Container sollte auf Port 80 verfügbar sein.

          Lösungsvorschläge bei Verbindungsproblemen:
          - Firewall-Regeln prüfen: sudo ufw status
          - Container-Logs prüfen: docker logs michaelschiemer_nginx
          - Container neu starten: cd {{ deploy_root }} && docker-compose restart nginx
