---

- name: Include OS specific variables
  include_vars: "{{ ansible_distribution }}.yml"

- name: Install packages
  include_tasks: "setup/{{ ansible_distribution }}.yml"

- name: Get IP range.
  shell: "echo {{ network_allowed }} | cut -d'.' --fields=1,2,3"
  register: ipresult

- name: Get interface name.
  shell: "ip -4 addr show | grep {{ ipresult.stdout }} | rev | cut -d ' ' -f 1 | rev"
  register: itfn

- name: Set keepalived_bind_interface.
  set_fact:
    keepalived_bind_interface: "{{ itfn.stdout }}"

- name: "Check if keepalived exists"
  stat:
    path: "/usr/sbin/keepalived"
  register: result

- name: Download keepalived archive
  get_url:
    url: "{{ keepalived_url }}"
    dest: /tmp/{{ keepalived_tar }}
    validate_certs: false
  when: not result.stat.exists

- name: Extract keepalived
  unarchive:
    src: /tmp/{{ keepalived_tar }}
    dest: "/tmp"
    remote_src: true
  when: not result.stat.exists

- name: Build keepalived with openssl
  shell: "{{ item }}"
  args:
    chdir: "/tmp/keepalived-{{ keepalived_version }}"
  with_items:
    - ./configure
    - make
    - make install
  when: not result.stat.exists

- name: Dropping the binary file
  copy:
    src: "/tmp/keepalived-{{ keepalived_version }}/keepalived/keepalived"
    dest: "/usr/sbin/keepalived"
    mode: "0755"
    owner: root
    group: root
    remote_src: yes
  when: not result.stat.exists

- name: Dropping the service file
  copy:
    src: "/tmp/keepalived-{{ keepalived_version }}/keepalived/etc/init.d/keepalived"
    dest: "/etc/init.d/keepalived"
    mode: "0755"
    owner: root
    group: root
    remote_src: yes
  when: not result.stat.exists

- name: Create a directory in etc
  file:
    path: /etc/keepalived
    state: directory
    mode: '0755'
    owner: root
    group: root
  when: not result.stat.exists

- name: Dropping the sysconfig file
  copy:
    src: "/tmp/keepalived-{{ keepalived_version }}/keepalived/etc/sysconfig/keepalived"
    dest: "/etc/sysconfig/keepalived"
    mode: "0644"
    owner: root
    group: root
    remote_src: yes
  when: not result.stat.exists

- name: Output keepalived version
  command: keepalived --version
  register: _keepalived_version
  changed_when: false
  check_mode: no

- name: Recursively remove installer
  file:
    path: "/tmp/keepalived-{{ keepalived_version }}"
    state: absent
  when: not result.stat.exists

- name: Ensure keepalived conf is set 
  template:
    src: keepalived.conf.j2
    dest: /etc/keepalived/keepalived.conf
    mode: 0640

- name: Ensuring keepalived is enabled and started
  service:
    daemon_reload: yes
    name: "{{ keepalived_service_name }}"
    state: "started"
    enabled: "yes"
    masked: "no"
