---
- name: Validate Docker Compose configuration
  command:
    cmd: docker compose -f {{ docker_compose.files.docker_compose }} config --quiet
    chdir: "{{ docker_compose.directories.instance }}"
  register: dc_validate
  changed_when: false
  failed_when: dc_validate.rc != 0
  listen:
    - docker compose up
    - docker compose restart
    - docker compose just up

- name: Build docker compose 
  shell: |
    set -euo pipefail
    docker compose build || { 
      echo "Retrying without cache and pulling bases...";
      docker compose build --no-cache --pull; 
    }
  args:
    chdir: "{{ docker_compose.directories.instance }}"
    executable: /bin/bash
  environment:
    COMPOSE_HTTP_TIMEOUT: 600
    DOCKER_CLIENT_TIMEOUT: 600
    # Faster build
    DOCKER_BUILDKIT: "1"
    COMPOSE_DOCKER_CLI_BUILD: "1"
  listen:
    - docker compose build

- name: docker compose up
  shell: |
    if [ -f "{{ docker_compose.files.env }}" ]; then
      docker compose -p {{ application_id | get_entity_name }} --env-file "{{ docker_compose.files.env }}" up -d --force-recreate --remove-orphans
    else
      docker compose -p {{ application_id | get_entity_name }} up -d --force-recreate --remove-orphans
    fi
  args:
    chdir: "{{ docker_compose.directories.instance }}"
    executable: /bin/bash
  environment:
    COMPOSE_HTTP_TIMEOUT: 600
    DOCKER_CLIENT_TIMEOUT: 600
  listen:
    - docker compose up
    - docker compose just up # @todo replace later just up by up when code is refactored, build atm is also listening to up

- name: docker compose restart
  command:
    cmd: 'docker compose restart'
    chdir: "{{ docker_compose.directories.instance }}"
  listen: docker compose restart
