---
- name: OVS | ensure requirements are installed
  action: "{{ ovs_package_info.pkg_mgr }}"
  args:
    pkg: "{{item.name}}"
    force: "{{item.force|default(omit)}}"
    state: present
  register: ovs_task_result
  until: ovs_task_result|succeeded
  retries: 3
  with_items: "{{ ovs_package_info.pkgs }}"

- name: OVS | get release build
  get_url:
    url: "{{ ovs_info.release_link }}"
    dest: "{{ ovs_info.build_path }}/{{ ovs_info.release_name }}.tar.gz"
    force_basic_auth: yes
    mode: 0755
    timeout: 30
  retries: 3

- name: OVS | Remove directory if it exists
  file:
    path: "{{ ovs_info.build_path }}/{{ ovs_info.release_name }}"
    state: absent

- name: OVS | unarchive tar.gz
  unarchive:
    src: "{{ ovs_info.build_path }}/{{ ovs_info.release_name }}.tar.gz"
    dest: "{{ ovs_info.build_path }}"
    remote_src: yes

- name: OVS | Build deb packages
  shell: |
    set -e
    dpkg-checkbuilddeps
    fakeroot debian/rules clean
    DEB_BUILD_OPTIONS='nocheck parallel=4' fakeroot debian/rules binary
  args:
    chdir: "{{ ovs_info.build_path }}/{{ ovs_info.release_name }}"

- name: OVS | install datapath debs
  apt: deb="{{ ovs_info.build_path }}/{{item}}_{{ ovs_info.pkg_build_version }}_all.deb"
  with_items:
    - openvswitch-datapath-dkms
    - python-openvswitch

- name: OVS | add modules
  lineinfile:
    path: "{{ ovs_info.modules_file_path }}"
    create: yes
    line: |
      openvswitch
      vport_stt
      vport_geneve

- name: OVS | reload modules
  action: shell depmod -a

- name: OVS | remove modprobe
  modprobe:
    name: "{{item}}"
    state: absent
  with_items:
    - openvswitch
    - vport-geneve
    - vport-stt

- name: OVS | add modprobe
  modprobe:
    name: "{{item}}"
    state: present
  with_items:
    - openvswitch
    - vport-geneve
    - vport-stt

- name: OVS | install debs
  apt: deb="{{ ovs_info.build_path }}/{{item}}_{{ ovs_info.pkg_build_version }}_amd64.deb"
  with_items:
    - libopenvswitch
    - openvswitch-common
    - openvswitch-switch
    - ovn-common
    - ovn-host

- name: OVS | install controller deb if applicable
  apt: deb="{{ ovs_info.build_path }}/ovn-central_{{ ovs_info.pkg_build_version }}_amd64.deb"
  when: controller

# TODO: .deb packages are not creating services, we need this for ovnkube
# when it tries to start/restart services
- name: OVS | Mock OVS services
  lineinfile:
    path: "{{item}}"
    create: yes
    line: |
      [Unit]
      Description=openvswitch
      Documentation=https://github.com/openvswitch/ovs
      [Service]
      ExecStart=/bin/bash sleep 1
      [Install]
      WantedBy=multi-user.target
  with_items:
    - /etc/systemd/system/openvswitch.service
    - /etc/systemd/system/ovn-controller.service
    - /etc/systemd/system/ovn-northd.service
