---

- name: "Ensure {{ apt_keyring_dir }} directory exists"
  file:
    path: "{{ apt_keyring_dir }}"
    state: directory
    mode: "755"
    owner: root
    group: root

- name: Yarn GPG key is installed
  ansible.builtin.copy:
    src: yarn.asc
    dest: "{{ apt_keyring_dir }}/yarn.asc"
    mode: "0644"
    owner: root
    group: root
  tags:
    - system
    - packages
    - nodejs
    - yarn

- name: Add Yarn repository (Debian <12)
  ansible.builtin.apt_repository:
    repo: "deb [signed-by={{ apt_keyring_dir }}/yarn.asc] https://dl.yarnpkg.com/debian/ stable main"
    filename: yarn
    state: present
  tags:
    - system
    - packages
    - nodejs
    - yarn
  when: ansible_distribution_major_version is version('12', '<')

- name: Add Yarn repository (Debian >=12)
  ansible.builtin.template:
    src: yarn.sources.j2
    dest: /etc/apt/sources.list.d/yarn.sources
    state: present
    update_cache: yes
  register: yarn_sources
  tags:
    - system
    - packages
    - nodejs
    - yarn
  when: ansible_distribution_major_version is version('12', '>=')

- name: Update APT cache
  ansible.builtin.apt:
    update_cache: yes
  when: yarn_sources is changed

- name: Yarn is installed
  ansible.builtin.apt:
    name: yarn
    state: present
  tags:
    - packages
    - nodejs
    - yarn
