- name: Certbot + Plugin installieren
  apt:
    name:
      - certbot
      - python3-certbot-nginx
    state: present
    update_cache: yes
  when: letsencrypt_enabled

- name: Challenge-Verzeichnis für Let's Encrypt anlegen
  file:
    path: "{{ app_public }}/.well-known/acme-challenge"
    state: directory
    owner: www-data
    group: www-data
    mode: '0755'
    recurse: yes
  when: letsencrypt_enabled and letsencrypt_certbot_method == 'webroot'

- name: Stoppe Nginx für Standalone-Methode
  service:
    name: nginx
    state: stopped
  when: letsencrypt_enabled and letsencrypt_certbot_method == 'standalone'

- name: Let's Encrypt Zertifikat anfordern (Standalone)
  command: >
    certbot certonly --standalone -n --agree-tos
    -m {{ app_email }}
    -d {{ app_domain }}
  args:
    creates: /etc/letsencrypt/live/{{ app_domain }}/fullchain.pem
  when: letsencrypt_enabled and letsencrypt_certbot_method == 'standalone'

- name: Let's Encrypt Zertifikat anfordern (Webroot)
  command: >
    certbot certonly --webroot -w {{ app_public }} -n --agree-tos
    -m {{ app_email }}
    -d {{ app_domain }}
  args:
    creates: /etc/letsencrypt/live/{{ app_domain }}/fullchain.pem
  when: letsencrypt_enabled and letsencrypt_certbot_method == 'webroot'

- name: Kopiere SSL-Zertifikate für Docker
  copy:
    src: "/etc/letsencrypt/live/{{ app_domain }}/"
    dest: "{{ app_root }}/ssl/"
    remote_src: yes
    mode: '0644'
  when: letsencrypt_enabled
