---
- name: Set fact on vip creation
  ansible.builtin.set_fact:
    vip_created: true
  run_once: true

- name: Check for vip existence
  ansible.builtin.command: "om system/svc/vip ls"
  changed_when: false
  register: svcvip
  run_once: true

- name: Set fact according to actual vip existence
  ansible.builtin.set_fact:
    vip_created: false
  run_once: true
  when:
    - "'system/svc/vip' not in svcvip.stdout"

- name: Identify node ip used for production
  ansible.builtin.shell: set -o pipefail && grep -w {{ ansible_hostname }} /etc/hosts | head -1 | awk '{print $1}'
  args:
    executable: /bin/bash
  changed_when: false
  register: grepquery
  when:
    - not vip_created

- name: Set fact according to command result
  ansible.builtin.set_fact:
    osvc_node_prd_ip: "{{ grepquery.stdout }}"
  when:
    - not vip_created

- name: Identify node nic used for production
  ansible.builtin.shell: set -o pipefail && ip route ls | grep {{ osvc_node_prd_ip }} | head -1 | grep -Po '(?<=dev )(\S+)'
  args:
    executable: /bin/bash
  register: iproutequery
  changed_when: false
  when:
    - not vip_created

- name: Set fact according to command result
  ansible.builtin.set_fact:
    osvc_node_prd_nic: "{{ iproutequery.stdout }}"
  when:
    - not vip_created

- name: Add cluster vip
  ansible.builtin.shell:
    "om cluster set
    --kw cluster.vip@{{ ansible_hostname }}={{ osvc_cluster_vip_addr }}/{{ osvc_cluster_vip_cidr_subnet }}\
    @{{ osvc_cluster_vip_nic_name }}@{{ osvc_node_prd_nic }} && sleep 5"
  throttle: 1
  register: output
  changed_when: output.rc == 0
  when:
    - not vip_created
    - nodecount|int > 1

- name: Add cluster vip (single-node)
  ansible.builtin.command: >-
    om cluster set --kw cluster.vip@{{ ansible_hostname }}=
    {{ osvc_cluster_vip_addr }}/{{ osvc_cluster_vip_cidr_subnet }}@{{ osvc_node_prd_nic }}
  run_once: true
  register: output
  changed_when: output.rc == 0
  when:
    - not vip_created
    - nodecount|int == 1

- name: Wait for vip service instance to be spawned
  ansible.builtin.command: 'sleep 5'
  run_once: true
  changed_when: false
  when:
    - not vip_created

- name: Unfreeze vip service
  ansible.builtin.command: 'om system/svc/vip thaw'
  run_once: true
  register: output
  changed_when: output.rc == 0
  when:
    - not vip_created
