- name: install EPEL Repository
  yum:
    name: epel-release
    state: latest
    disable_gpg_check: yes
  when: (ansible_facts['os_family'] == "RedHat" or ansible_facts['os_family'] == 'CentOS') and HAPVER|length > 0
  ignore_errors: yes
  environment:
    http_proxy: "{{PROXY}}"
    https_proxy: "{{PROXY}}"

- name: Set dist short name if EL
  set_fact:
    distr_short_name: "el"
  when: ansible_facts['os_family'] == "RedHat" or ansible_facts['os_family'] == 'CentOS'

- name: Set dist short name if Amazon Linux
  set_fact:
    distr_short_name: "amzn"
  when: ansible_distribution == "Amazon"

- name: install HAProxy {{HAPVER}} on {{distr_short_name}}{{ansible_facts['distribution_major_version']}}
  yum:
    name:
      - http://repo.roxy-wi.org/haproxy/haproxy-{{HAPVER}}.{{distr_short_name}}{{ansible_facts['distribution_major_version']}}.x86_64.rpm
      - socat
      - rsyslog
    state: present
    disable_gpg_check: yes
  when: (ansible_facts['os_family'] == "RedHat" or ansible_facts['os_family'] == 'CentOS') and HAPVER|length > 0
  ignore_errors: yes
  register: install_result
  retries: 5
  until: install_result.rc == 0
  delay: 5
  environment:
    http_proxy: "{{PROXY}}"
    https_proxy: "{{PROXY}}"

- name: Try to install another HAProxy {{HAPVER}} on {{distr_short_name}}{{ansible_facts['distribution_major_version']}}
  yum:
    name:
      - http://repo1.roxy-wi.org/haproxy/haproxy-{{HAPVER}}.{{distr_short_name}}{{ansible_facts['distribution_major_version']}}.x86_64.rpm
      - socat
      - rsyslog
      - bind-utils
    state: present
  when: (ansible_facts['os_family'] == "RedHat" or ansible_facts['os_family'] == 'CentOS') and ("'timed out' in install_result.stderr")
  ignore_errors: yes
  register: install_result1
  retries: 5
  until: install_result1.rc == 0
  delay: 5
  environment:
    http_proxy: "{{PROXY}}"
    https_proxy: "{{PROXY}}"


- name: set_fact from wi
  set_fact:
    haproxy_from_wi: "yes"
  when: (ansible_facts['os_family'] == "RedHat" or ansible_facts['os_family'] == 'CentOS' or ansible_distribution == 'Amazon') and HAPVER|length > 0


- name: install the latest version of HAProxy
  yum:
    name:
      - haproxy
      - socat
      - rsyslog
    state: latest
  when: (ansible_facts['os_family'] == "RedHat" or ansible_facts['os_family'] == 'CentOS') and (install_result.rc != 0 and install_result1.rc != 0)
  register: install_result
  retries: 5
  until: install_result.rc == 0
  delay: 5
  environment:
    http_proxy: "{{PROXY}}"
    https_proxy: "{{PROXY}}"


- name: Install HAProxy
  apt:
    name:
      - haproxy
      - socat
      - rsyslog
    state: present
  when: ansible_facts['os_family'] == 'Debian' or ansible_facts['os_family'] == 'Ubuntu'
  environment:
    http_proxy: "{{PROXY}}"
    https_proxy: "{{PROXY}}"

- name: Enable and start service HAProxy
  systemd:
    name: haproxy
    daemon_reload: yes
    state: started
    enabled: yes
    force: yes
  ignore_errors: yes
