---
- name: Local Loopback Deployment Operations
  hosts: minipc
  gather_facts: false
  tasks:
    - name: Check if prometheus.yml is a directory
      ansible.builtin.stat:
        path: /opt/homelab/data/prometheus/prometheus.yml
      register: prom_stat

    - name: Remove prometheus.yml if it is a directory
      ansible.builtin.file:
        path: /opt/homelab/data/prometheus/prometheus.yml
        state: absent
      when: prom_stat.stat.isdir is defined and prom_stat.stat.isdir

    - name: Sync GitOps stacks to target machine
      ansible.posix.synchronize:
        src: "{{ playbook_dir }}/docker/stacks/"
        dest: /opt/homelab/stacks/
        archive: yes
        delete: no
        recursive: yes
        rsync_opts:
          - "--exclude=.git"
          - "--exclude=.gitignore"

    - name: Sync GitOps data to target machine
      ansible.posix.synchronize:
        src: "{{ playbook_dir }}/docker/data/"
        dest: /opt/homelab/data/
        archive: yes
        delete: no
        recursive: yes
        rsync_opts:
          - "--exclude=.git"
          - "--exclude=.gitignore"

    - name: Identify all docker-compose stack directories
      ansible.builtin.find:
        paths: /opt/homelab/stacks
        file_type: file
        patterns: "docker-compose.yml"
        recurse: yes
      register: compose_files

    - name: Apply Docker Compose configurations
      ansible.builtin.command: docker compose up -d --remove-orphans
      args:
        chdir: "{{ item.path | dirname }}"
      loop: "{{ compose_files.files }}"
      register: compose_results
      changed_when: "'Started' in compose_results.stdout or 'Created' in compose_results.stdout or 'Recreated' in compose_results.stdout"