---

- name: Install needed tools
  package:
    name:
      - tar
      - zstd
      - unzip
  tags: consul

- when: consul_install_mode != 'none'
  block:
    - name: Download consul
      get_url:
        url: "{{ consul_archive_url }}"
        dest: "{{ consul_root_dir }}/tmp"
        checksum: sha256:{{ consul_archive_sha256 }}

    - name: Extract the archive
      unarchive:
        src: "{{ consul_root_dir }}/tmp/consul_{{ consul_version }}_linux_amd64.zip"
        dest: "{{ consul_root_dir }}/tmp"
        remote_src: True

    - name: Install consul binary
      copy:
        src: "{{ consul_root_dir }}/tmp/consul"
        dest: "{{ consul_root_dir }}/bin/consul"
        remote_src: True
        mode: 755

    - name: Link in /usr/local/bin
      file: src={{ consul_root_dir }}/bin/consul dest=/usr/local/bin/consul state=link force=True

  tags: consul

- name: Install bash completion support
  copy:
    content: |
      complete -C {{ consul_root_dir }}/bin/consul consul
    dest: /etc/bash_completion.d/consul
    mode: 755
  tags: consul

- name: Deploy systemd service unit
  template: src=consul.service.j2 dest=/etc/systemd/system/consul.service
  register: consul_unit
  notify: restart consul
  tags: consul

- name: Reload systemd
  systemd: daemon_reload=True
  when: consul_unit.changed
  tags: consul

- name: Install backup hooks
  template: src={{ item }}-backup.j2 dest=/etc/backup/{{ item }}.d/consul mode=755
  loop:
    - pre
    - post
  tags: consul
