---
- name: Ensure dependencies are present.
  become: yes
  apt:
    name:
      - apt-transport-https
      - gnupg2
      - build-essential
    state: present

- name: Add Nodesource apt key.
  become: yes
  apt_key:
    url: https://keyserver.ubuntu.com/pks/lookup?op=get&fingerprint=on&search=0x1655A0AB68576280
    id: "68576280"
    state: present

- name: Add NodeSource repositories for Node.js.
  become: yes
  apt_repository:
    repo: "{{ item }}"
    state: present
  with_items:
    - "deb https://deb.nodesource.com/node_{{ nodejs_version }} {{ ansible_distribution_release }} main"
    - "deb-src https://deb.nodesource.com/node_{{ nodejs_version }} {{ ansible_distribution_release }} main"
  register: node_repo

- name: Update apt cache if repo was added.
  become: yes
  apt:
    update_cache: true
    cache_valid_time: 43200   # 12 hours
  when: node_repo.changed
  tags: ['skip_ansible_lint']

- name: Ensure Node.js and npm are installed.
  become: yes
  apt:
    name: "nodejs={{ nodejs_version|regex_replace('x', '') }}*"
    state: present
