---
- name: Deployment in jeweilige Umgebung
  hosts: web
  become: true
  gather_facts: true

  vars:
    project_source: "{{ playbook_dir }}/../.."
    docker_compose_project_path: "{{ deploy_root }}"

  pre_tasks:
    - name: Überprüfe Server-Verbindung
      ping:
      tags: [always, check]

    - name: Zeige Server-Informationen
      debug:
        msg: "Verbunden mit {{ inventory_hostname }} ({{ ansible_host | default('IP unbekannt') }})"
      tags: [always, check]

  roles:
    - common
    - docker
    - nginx

  tasks:
    - name: Stelle sicher, dass Zielverzeichnisse existieren
      file:
        path: "{{ item }}"
        state: directory
        owner: "{{ deploy_user }}"
        group: "{{ deploy_user }}"
        mode: '0755'
      loop:
        - "{{ deploy_root }}"
        - "{{ deploy_root }}/public"
        - "{{ deploy_root }}/ssl"
        - "{{ deploy_root }}/src"
        - "{{ deploy_root }}/docker"
        - "{{ deploy_root }}/docker/nginx"
        - "{{ deploy_root }}/docker/php"
      tags: [deploy, folders]

    - name: Kopiere Docker-Konfigurationen
      copy:
        src: "{{ playbook_dir }}/../docker/"
        dest: "{{ deploy_root }}/docker/"
        mode: '0644'
        owner: "{{ deploy_user }}"
        group: "{{ deploy_user }}"
      tags: [deploy, docker]

    - name: Kopiere docker-compose.yml
      copy:
        src: "{{ playbook_dir }}/../docker-compose.yml"
        dest: "{{ deploy_root }}/docker-compose.yml"
        mode: '0644'
        owner: "{{ deploy_user }}"
        group: "{{ deploy_user }}"
      tags: [deploy, docker]

    - name: Container starten oder neustarten
      ansible.builtin.shell: |
        cd "{{ deploy_root }}" && \
        docker-compose -f docker-compose.yml -p michaelschiemer up -d --build
      tags: [deploy, docker]

  post_tasks:
    - name: Überprüfe Anwendungsstatus
      uri:
        url: "http://{{ ansible_host }}/"
        return_content: no
        status_code: 200, 301, 302, 403, 404
        validate_certs: no
        timeout: 10
      register: app_status
      ignore_errors: yes
      delegate_to: localhost
      become: no
      tags: [check]

    - name: Zeige Deployment-Ergebnis
      debug:
        msg: |
          Deployment abgeschlossen:
          - Server: {{ inventory_hostname }}
          - Umgebung: {{ environment | default('unbekannt') }}
          - Status: {% if app_status.status is defined and app_status.status == 200 %}Erfolgreich (HTTP 200){% else %}Überprüfung erforderlich{% endif %}

          Anwendung sollte erreichbar sein unter: http://{{ ansible_host }}/
      tags: [check]

