---
- block:
  - name: Remove the openjdk-r ppa. It is not maintained anymore
    apt_repository: repo='{{ dismissed_openjdk_ppa }}' update_cache=yes state=absent

  - name: Remove the Oracle JDK PPA
    apt_repository: repo='{{ oracle_jdk_ubuntu_ppa }}' state=absent update_cache=yes

  - name: Check if we must use the Zulu repository
    set_fact:
      openjdk_zulu_repo_install: True
    when: ansible_distribution_major_version <= '16'

  tags: [ 'jdk', 'openjdk' ]

- block:
  - name: Install the Zulu repository key
    apt_key: keyserver='hkp://keyserver.ubuntu.com' id={{ openjdk_zulu_repo_key_id }}

  - name: Install the proper Zulu repository
    apt_repository: repo='{{ openjdk_zulu_repository }}' update_cache=yes

  - name: Install the Zulu OpenJDK 
    apt: pkg={{ openjdk_zulu_package_name }}-{{ item }} state={{ openjdk_pkg_state }} update_cache=yes cache_valid_time=3600
    with_items: '{{ openjdk_version }}'
    register: openjdk_installed

  - name: Set the default OpenJDK as Zulu
    shell: update-java-alternatives -s /usr/lib/jvm/zulu-{{ openjdk_default }}-amd64
    when: openjdk_installed is changed

  - name: Set the correct value for jdk_java_home when we are installing Zulu
    set_fact:
      jdk_java_home: '{{ openjdk_zulu_java_home }}'

  when: openjdk_zulu_repo_install
  tags: [ 'jdk', 'openjdk' ]

- block:
  - name: Remove the Zulu repository if it is present
    apt_repository: repo='{{ openjdk_zulu_repository }}' update_cache=yes state=absent

  - name: Install the OpenJDK that comes with the distribution
    apt: pkg=openjdk-{{ item.0 }}-{{ item[1] }} state={{ openjdk_pkg_state }} update_cache=yes cache_valid_time=3600
    with_nested:
      - '{{ openjdk_version }}'
      - '{{ openjdk_pkgs }}'
    register: openjdk_installed

  - name: Set the default OpenJDK
    shell: update-java-alternatives -s java-1.{{ openjdk_default }}.0-openjdk-amd64
    when: openjdk_installed is changed

  - name: Set the correct value for jdk_java_home when we are installing the distribution OpenJDK
    set_fact:
      jdk_java_home: '{{ openjdk_java_home }}'

  when: not openjdk_zulu_repo_install
  tags: [ 'jdk', 'openjdk' ]

- block:
  - name: Rebuild the Ubuntu keystore
    command: update-ca-certificates --fresh
    when: openjdk_installed is changed

  tags: [ 'jdk', 'openjdk' ]

- block:
  - name: Remove the Oracle JDK packages
    apt: pkg={{ openjdk_oracle_jdk_pkgs }} state=absent cache_valid_time=3600

  - name: Remove the OpenJDK packages fthat come with the distribution when we use the Zulu repository
    apt: pkg=openjdk-{{ item.0 }}-{{ item[1] }} state=absent update_cache=yes cache_valid_time=3600
    with_nested:
      - '{{ openjdk_version }}'
      - '{{ openjdk_pkgs }}'
    when: openjdk_zulu_repo_install

  tags: [ 'jdk', 'openjdk' ]