---
- name: Check if already installed
  command: dpkg-query  --show --showformat='${db:Status-Abbrev}' {{ item }}
  with_items:
    - ofed-scripts
    - mlnx-ofed-kernel-utils
    - mlnx-ofed-kernel-dkms
    - iser-dkms
    - isert-dkms
    - kernel-mft-dkms
    - knem-dkms
    - knem
  check_mode: no
  failed_when: false
  changed_when: false
  register: dpkg_query

- set_fact:
    rdma_driver_installed: >-
      {{
         dpkg_query['results'] | map(attribute='rc') | select('!=', 0) | list | length == 0
           and
         dpkg_query['results'] | map(attribute='stdout') | map('trim') | select('!=', 'ii') | list | length == 0
      }}

- name: Install MLNX drivers
  when:
    - ansible_distribution_version == '14.04'
    - not rdma_driver_installed
  block:
    # Downloaded from http://www.mellanox.com/downloads/ofed/MLNX_OFED-4.2-1.2.0.0/MLNX_OFED_LINUX-4.2-1.2.0.0-ubuntu14.04-x86_64.tgz
    # Driver moved from /mnt/flashblade/sguo/*
    - name: Download MLNX_OFED driver tar
      get_url:
        dest: "{{ rdma_mlnx_install_dir }}{{ rdma_mlnx_driver_tar_name_14_04 }}"
        url: "https://z3.zooxlabs.com/zoox-third-party/{{ rdma_mlnx_driver_sha_14_04 }}/{{ rdma_mlnx_driver_tar_name_14_04 }}"

    - name: Extract MLNX_OFED driver tar
      unarchive:
        src: "{{ rdma_mlnx_install_dir }}{{ rdma_mlnx_driver_tar_name_14_04 }}"
        dest: "{{ rdma_mlnx_install_dir }}"
        remote_src: yes

    - name: Delete MLNX_OFED driver tar
      file:
        path: "{{ rdma_mlnx_install_dir }}{{ rdma_mlnx_driver_tar_name_14_04 }}"
        state: absent

    - name: Install MLNX_OFED driver
      shell: "{{ rdma_mlnx_driver_path_14_04 }}/{{ rdma_mlnx_setup_file }} --kernel-only --force"
      notify: restart openibd

    - name: Delete MLNX_OFED driver extraction
      file:
        path: "{{ rdma_mlnx_driver_path_14_04 }}"
        state: absent

- name: Install MLNX drivers
  when:
    - ansible_distribution_version == '18.04'
    - not rdma_driver_installed
  block:
    # Driver moved from /mnt/flashblade/sguo/*
    - name: Download MLNX_OFED driver tar
      get_url:
        dest: "{{ rdma_mlnx_install_dir }}{{ rdma_mlnx_driver_tar_name_18_04 }}"
        url: "https://z3.zooxlabs.com/zoox-third-party/{{ rdma_mlnx_driver_sha_18_04 }}/{{ rdma_mlnx_driver_tar_name_18_04 }}"

    - name: Extract MLNX_OFED driver tar
      unarchive:
        src: "{{ rdma_mlnx_install_dir }}{{ rdma_mlnx_driver_tar_name_18_04 }}"
        dest: "{{ rdma_mlnx_install_dir }}"
        remote_src: yes

    - name: Delete MLNX_OFED driver tar
      file:
        path: "{{ rdma_mlnx_install_dir }}{{ rdma_mlnx_driver_tar_name_18_04 }}"
        state: absent

    - name: Install MLNX_OFED driver
      shell: "{{ rdma_mlnx_driver_path_18_04 }}/{{ rdma_mlnx_setup_file }} --kernel-only --force"
      notify: restart openibd

    - name: Delete MLNX_OFED driver extraction
      file:
        path: "{{ rdma_mlnx_driver_path_18_04 }}"
        state: absent
