- name: Deploy application
  hosts: "{{ target_host }}"
  vars:
    repo_path: "/home/{{ ansible_user }}/iac/docker/{{ folder }}"
    secrets_mapping_file: "/home/{{ ansible_user }}/iac/secret-mappings.yml"
  tasks:
    - name: Read secret mapping
      ansible.builtin.slurp:
        src: "{{ secrets_mapping_file }}"
      register: secret_mapping_content

    - name: Parse secret mapping
      ansible.builtin.set_fact:
        secret_mapping: "{{ secret_mapping_content['content'] | b64decode | from_yaml }}"

    - name: Set env_variables
      ansible.builtin.set_fact:
        env_variables: "{{ secret_mapping[target_host]['env_variables'] | default({}) }}"

    - name: Write .env file to target host
      ansible.builtin.copy:
        dest: "{{ repo_path }}/.env"
        content: |
          {% for key, secret_id in env_variables.items() %}
          {{ key }}={{ lookup('bitwarden.secrets.lookup', secret_id, access_token=bw_access_token) }}
          {% endfor %}

    - name: Ensure the repository is up-to-date
      ansible.builtin.shell: git pull
      args:
        chdir: "{{ repo_path }}"
      register: git_pull_output

    - name: Display git pull output
      ansible.builtin.debug:
        var: git_pull_output.stdout_lines

    - name: Restart services using Docker Compose
      community.docker.docker_compose_v2:
        project_src: "{{ repo_path }}"
        state: present
        remove_orphans: true

    - name: Run Docker Command
      command: docker compose ps
      args:
        chdir: "{{ repo_path }}"
      register: docker_output

    - name: Display Docker Output
      debug:
        var: docker_output.stdout_lines