---
- name: register latest installed kernel version
  shell: |
    rpm -qa | grep ^kernel-[0-9] | sort | tail -1 | awk -F 'kernel-' {'print $2'}
  register: installed_kernel

- name: register loaded kernel
  command: uname -r
  register: loaded_kernel

- name: register installed openvswitch package version
  shell: |
    rpm --queryformat %{VERSION} -q openvswitch | awk -F "." '{print $1"."$2}'
  register: installed_ovs

- name: register loaded openvswitch version
  shell: |
    ovs-vsctl show | grep ovs_version | awk -F \" {'print $2'} | awk -F "." '{print $1"."$2}'
  become: true
  become_user: root
  register: loaded_ovs

- name: handle undercloud reboot
  block:
    - name: reboot the undercloud
      shell: "sleep 2 && shutdown -r now"
      async: 1
      poll: 0
      ignore_errors: true
      become: true
      become_user: root

    - name: wait for node to go down
      become: false
      command: ping -c1 {{ ansible_host }}
      register: node_down
      until: node_down.rc != 0
      retries: 60
      delay: 3
      ignore_errors: true
      delegate_to: localhost
      when: "'hypervisor' not in groups and 'virthost' not in groups"

    - name: wait for node to go down
      command: ping -c1 {{ ansible_host }}
      register: node_down
      until: node_down.rc != 0
      retries: 60
      delay: 3
      ignore_errors: true
      delegate_to: hypervisor
      when: "'hypervisor' in groups"

    - name: wait for node to go down
      command: ping -c1 {{ ansible_host }}
      register: node_down
      until: node_down.rc != 0
      retries: 60
      delay: 3
      ignore_errors: true
      delegate_to: virthost
      when: "'virthost' in groups"

    - name: waiting for the undercloud to be ssh-able
      wait_for_connection:
        connect_timeout: 5
        sleep: 3
        timeout: 630

    - name: assert UC services started
      shell: |
        source {{ undercloud_rc }} ;
        timeout 10 openstack stack list -f json | jq -c -r '.[]|.["Stack Name"]'
      ignore_errors: true
      register: oc_name
      until: oc_name.stdout.find('{{ overcloud_stack_name }}') != -1
      retries: "{{ service_readiness_count|default(100)|int }}"
      delay: 3
  when:
    - not tripleo_ci
    - >
      undercloud_reboot or
      (installed_kernel.stdout != loaded_kernel.stdout) or
      (installed_ovs.stdout != loaded_ovs.stdout)
  tags: undercloud_reboot
