---
# Fallback Deployment für Debian (mit allen Variablen)

- name: Deploy App to Netcup VPS (Debian Fallback)
  hosts: all
  become: yes
  vars_files:
    - inventory/group_vars.yml
  
  tasks:
    - name: Update system
      apt:
        update_cache: yes
        upgrade: dist
        
    - name: Install packages from Debian repos
      apt:
        name:
          - nginx
          - certbot
          - python3-certbot-nginx
          - git
          - curl
          - rsync
          - docker.io
          - docker-compose
        state: present
        
    - name: Start and enable Docker
      systemd:
        name: docker
        state: started
        enabled: yes
        
    - name: Add user to docker group
      user:
        name: "{{ ansible_user }}"
        groups: docker
        append: yes
        
    - name: Deploy webapp
      include_role:
        name: webapp
        
    - name: Configure Nginx reverse proxy
      template:
        src: roles/webapp/templates/nginx-site.conf.j2
        dest: /etc/nginx/sites-available/{{ domain }}
        backup: yes
      notify: reload nginx
      
    - name: Enable site
      file:
        src: /etc/nginx/sites-available/{{ domain }}
        dest: /etc/nginx/sites-enabled/{{ domain }}
        state: link
      notify: reload nginx
      
    - name: Remove default site
      file:
        path: /etc/nginx/sites-enabled/default
        state: absent
      notify: reload nginx
      
    - name: Generate SSL certificate
      command: >
        certbot --nginx -d {{ domain }}
        --non-interactive --agree-tos
        --email {{ ssl_email }}
      args:
        creates: "/etc/letsencrypt/live/{{ domain }}/fullchain.pem"
        
    - name: Setup SSL renewal
      cron:
        name: "Renew SSL"
        minute: "0"
        hour: "3"
        job: "certbot renew --quiet"
        
    - name: Start nginx
      systemd:
        name: nginx
        state: started
        enabled: yes
        
    - name: Wait for app to be ready
      wait_for:
        port: 80
        delay: 10
        timeout: 60
        
    - name: Health check
      uri:
        url: "https://{{ domain }}"
        method: GET
        status_code: [200, 301, 302]
      retries: 5
      delay: 10
      ignore_errors: yes
      
  handlers:
    - name: reload nginx
      systemd:
        name: nginx
        state: reloaded
