---

# This snippet determines if a Docker upgrade is required by checking the inventory
# variables, the available packages, and sets l_docker_upgrade to True if so.

- set_fact:
    docker_upgrade: True
  when: docker_upgrade is not defined

- name: Check if Docker is installed
  command: rpm -q docker
  register: pkg_check
  failed_when: pkg_check.rc > 1
  changed_when: no

- name: Get current version of Docker
  command: "{{ repoquery_cmd }} --installed --qf '%{version}' docker"
  register: curr_docker_version
  changed_when: false

- name: Get latest available version of Docker
  command: >
    {{ repoquery_cmd }} --qf '%{version}' "docker"
  register: avail_docker_version
  # Don't expect docker rpm to be available on hosts that don't already have it installed:
  when: pkg_check.rc == 0
  failed_when: false
  changed_when: false

- fail:
    msg: This playbook requires access to Docker 1.10 or later
  # Disable the 1.10 requirement if the user set a specific Docker version
  when: docker_version is not defined and (docker_upgrade is not defined or docker_upgrade | bool == True) and (pkg_check.rc == 0 and (avail_docker_version.stdout == "" or avail_docker_version.stdout | version_compare('1.10','<')))

# Default l_docker_upgrade to False, we'll set to True if an upgrade is required:
- set_fact:
    l_docker_upgrade: False

# Make sure a docker_verison is set if none was requested:
- set_fact:
    docker_version: "{{ avail_docker_version.stdout }}"
  when: pkg_check.rc == 0 and docker_version is not defined

- name: Flag for Docker upgrade if necessary
  set_fact:
    l_docker_upgrade: True
  when: pkg_check.rc == 0 and curr_docker_version.stdout | version_compare(docker_version,'<')

- name: Flag to delete all images prior to upgrade if crossing Docker 1.10 boundary
  set_fact:
      docker_upgrade_nuke_images: True
  when: l_docker_upgrade | bool and docker_upgrade_nuke_images is not defined and curr_docker_version.stdout | version_compare('1.10','<') and docker_version | version_compare('1.10','>=')

