---
# Fail as early as possible if Atomic and old version of Docker
- block:
  - name: Determine Atomic Host Docker Version
    shell: 'CURLY="{"; docker version --format "$CURLY{json .Server.Version}}"'
    register: l_atomic_docker_version

  - assert:
      msg: Installation on Atomic Host requires Docker 1.12 or later. Attempting to patch.
      that:
      - l_atomic_docker_version.stdout | replace('"', '') | version_compare('1.12','>=')

  rescue:
  - name: Is the host already registered?
    command: "subscription-manager status"
    register: subscribed
    changed_when: no
    ignore_errors: yes
    when: ansible_distribution == "RedHat"

  - name: RedHat subscriptions
    redhat_subscription:
      username: "{{ rhsm_user }}"
      password: "{{ rhsm_password }}"
    when: "'Current' not in subscribed.stdout and rhsm_user is defined and rhel_subscription_user"

  - name: Retrieve the OpenShift Pool ID
    command: subscription-manager list --available --matches="{{ rhsm_pool }}" --pool-only
    register: openshift_pool_id
    changed_when: False
    when: ansible_distribution == "RedHat"

  - name: Determine if OpenShift Pool Already Attached
    command: subscription-manager list --consumed --matches="{{ rhsm_pool }}" --pool-only
    register: openshift_pool_attached
    changed_when: False
    when: openshift_pool_id.stdout == '' and ansible_distribution == "RedHat"

  - fail:
      msg: "Unable to find pool matching {{ rhsm_pool }} in available or consumed pools"
    when: openshift_pool_id.stdout == '' and openshift_pool_attached is defined and openshift_pool_attached.stdout == ''

  - name: Attach to OpenShift Pool
    command: subscription-manager subscribe --pool {{ openshift_pool_id.stdout_lines[0] }}
    when: openshift_pool_id.stdout != '' and ansible_distribution == "RedHat"

  - name: Patching Atomic instances
    shell: atomic host upgrade
    register: patched

  - name: Reboot when patched
    shell: sleep 5 && shutdown -r now "Reboot due to Atomic Patching"
    async: 1
    poll: 0
    ignore_errors: true
    when: patched.changed

  - name: Wait for hosts to be back
    pause:
      seconds: 60
    delegate_to: 127.0.0.1
    when: patched.changed

  when: openshift.common.is_atomic | bool
