---
- name: setup unattended-upgrades and apt-daily timers
  include_tasks: apt-auto-delay.yml

- name: Install GPG util
  apt:
    name: gpg
    state: present
    update_cache: yes

- name: Add GPG keys
  apt_key:
    url: "{{ item }}"
    state: present
  with_items: "{{ deb_gpg }}"

- name: Add additionnal APT repositories
  apt_repository:
    repo: "{{ item }}"
    state: present
  with_items: "{{ apt_repositories }}"

- name: Wait until dpkg lock files are released
  shell: while fuser {{ item }} >/dev/null 2>&1; do sleep 1; done;
  with_items: "{{ dpkg_lock_files }}"

- name: Uninstall a list of packages defined in uninstall_packages vars
  apt:
    name: "{{ uninstall_packages }}"
    state: absent
    autoclean: yes
    purge: yes
  register: apt_uninstall_result
  until: apt_uninstall_result.failed == false
  retries: 3
  delay: 10

- name: Install a list of packages defined in install_packages vars
  apt:
    name: "{{ install_packages }}"
    state: present
    install-recommends: false
    update_cache: yes
  register: apt_install_result
  until: apt_install_result.failed == false
  retries: 3
  delay: 10

- name: Install a list of packages for orchestrator instances
  apt:
    name: "{{ orchestrator_packages }}"
    state: present
    install-recommends: false
    update_cache: yes
  register: apt_install_result
  until: apt_install_result.failed == false
  retries: 3
  delay: 10
  when: layerops_instance_type == "orchestrator"

- name: Hold packages to prevent upgrades
  dpkg_selections:
    name: "{{ item }}"
    selection: hold
  with_items: "{{ hold_packages }}"
  when: hold_packages is defined

- name: Auto remove unused packages
  cron:
    name: "remove unused packages"
    job: "apt autoremove -y"
    minute: "0"
    hour: "3"
