---
# Playbook to provision Komodo stacks from git repository
# Automatically discovers stacks from docker-compose folder structure
# Structure: docker-compose/{server}/{app}/compose.yaml
# Usage: ansible-playbook -i inventories/production.yml playbooks/provision_komodo_stacks.yml

- name: Provision Komodo stacks
  hosts: localhost
  connection: local
  gather_facts: false

  vars:
    docker_compose_root: "{{ playbook_dir }}/../../docker-compose"

  tasks:
    - name: Find all compose.yaml files in docker-compose directory
      find:
        paths: "{{ docker_compose_root }}"
        patterns: "compose.yaml"
        recurse: true
      register: compose_files

    - name: Build stack list from discovered compose files
      set_fact:
        komodo_stacks: "{{ komodo_stacks | default([]) + [{'server': path_parts[0], 'app': path_parts[1]}] }}"
      loop: "{{ compose_files.files }}"
      vars:
        path_parts: "{{ item.path | regex_replace('^.*/docker-compose/', '') | split('/') }}"
      loop_control:
        label: "{{ path_parts[0] }}/{{ path_parts[1] }}"

    - name: Display discovered stacks
      debug:
        msg: "Found {{ komodo_stacks | length }} stacks: {{ komodo_stacks | map(attribute='app') | list | join(', ') }}"

    - name: Create Komodo stacks
      include_role:
        name: komodo_stack
      vars:
        komodo_stack_name: "{{ item.app }}"
        komodo_server_name: "{{ item.server }}"
        komodo_run_directory: "docker-compose/{{ item.server }}/{{ item.app }}"
      loop: "{{ komodo_stacks }}"
      loop_control:
        label: "{{ item.app }} (on {{ item.server }})"
