---
# Datei: ansible/playbooks/deploy/includes/project_sync.yml
# Verwaltet die Synchronisierung von Projektdateien

- name: Stelle sicher, dass das Zielverzeichnis existiert
  file:
    path: "{{ deploy_root }}"
    state: directory
    owner: "{{ deploy_user }}"
    group: "{{ deploy_user }}"
    mode: '0755'

- name: Synchronisiere Projektdateien (wenn project_source definiert ist)
  synchronize:
    src: "{{ project_source }}/"
    dest: "{{ deploy_root }}/"
    delete: yes
    rsync_opts:
      - "--exclude=.git/"
      - "--exclude=node_modules/"
      - "--exclude=vendor/"
      - "--exclude=.env.local"
  when: lookup('vars', 'project_source', default=false)

- name: SSL-Verzeichnis sicherstellen
  file:
    path: "{{ deploy_root }}/ssl"
    state: directory
    owner: "{{ deploy_user }}"
    group: "{{ deploy_user }}"
    mode: '0755'

- name: Public-Verzeichnis sicherstellen
  file:
    path: "{{ deploy_root }}/public"
    state: directory
    owner: "{{ deploy_user }}"
    group: "{{ deploy_user }}"
    mode: '0755'

- name: SSL-Zertifikate prüfen
  stat:
    path: "/etc/letsencrypt/live/{{ app_domain }}/fullchain.pem"
  register: ssl_certs
  when: ssl_enabled | default(false)

- name: SSL-Zertifikate kopieren (falls vorhanden)
  copy:
    src: "{{ item.src }}"
    dest: "{{ item.dest }}"
    remote_src: yes
    owner: "{{ deploy_user }}"
    group: "{{ deploy_user }}"
    mode: '0644'
  loop:
    - { src: "/etc/letsencrypt/live/{{ app_domain }}/fullchain.pem", dest: "{{ deploy_root }}/ssl/fullchain.pem" }
    - { src: "/etc/letsencrypt/live/{{ app_domain }}/privkey.pem", dest: "{{ deploy_root }}/ssl/privkey.pem" }
  when: ssl_enabled | default(false) and ssl_certs.stat.exists | default(false)

- name: .env-Datei erstellen oder aktualisieren
  template:
    src: templates/.env.j2
    dest: "{{ deploy_root }}/.env"
    owner: "{{ deploy_user }}"
    group: "{{ deploy_user }}"
    mode: '0644'
  when: lookup('vars', 'env_vars', default=false)
