---

- name: install dependencies
  apt:
    name:
      - liblua5.3-0
      - libpcre3
    state: present

- name: conflicted with haproxy package
  apt:
    name:
      - haproxy
    state: absent


- name: add user 'haproxy'
  user:
    name: haproxy
    system: yes
    create_home: no

- name: create directories
  file:
    path: "{{ item }}"
    state: directory
    mode: 0755
  with_items:
    - /etc/haproxy/
    - /etc/haproxy/certs/
    - /var/lib/haproxy/

- name: copy errorcodes
  copy:
    src: errorfiles
    dest: /etc/haproxy/
    mode: 0644

- name: copy haproxy binary
  copy:
    src: haproxy
    dest: /usr/local/bin
    mode: 0755
  notify:
    - restart haproxy

- name: copy scripts
  copy:
    src: "{{ item }}"
    dest: /usr/local/bin
    mode: 0755
  with_items:
    - update_haproxy_certs.sh
    - ocsp_update.sh

- name: create basic HAProxy configs
  template:
    src: "{{ item }}"
    dest: "/etc/haproxy/{{ item }}"
    mode: 0644
  with_items:
    - hostname2backend.map
    - haproxy.cfg
  notify: reload haproxy

- name: create domains files for certificate generation
  template:
    src: "{{ item }}"
    dest: /etc/haproxy/
    mode: 0644
  with_items:
    - domains.txt
    - all-domains.txt
  notify:
    - update certs

- name: systemd unit
  copy:
    src: haproxy.service
    dest: /lib/systemd/system/
    mode: 0644
  notify:
    - reload systemd config
    - reload haproxy

- name: haproxy service
  service:
    name: haproxy
    enabled: yes
    state: started

- name: renew certificates every sunday
  cron:
    name: renew certificates
    weekday: SUN
    minute: "{{ 59|random(seed=inventory_hostname+'renew certificates') }}"
    hour: "{{ 23|random(seed=inventory_hostname+'renew certificates') }}"
    job: /usr/local/bin/update_haproxy_certs.sh

- name: renew ocsp information
  cron:
    name: renew ocsp
    minute: "{{ 59|random(seed=inventory_hostname+'renew ocsp') }}"
    hour: "{{ 23|random(seed=inventory_hostname+'renew ocsp') }}"
    job: /usr/local/bin/ocsp_update.sh