---

- name: Deploy consul configuration
  block:
    - name: Deploy consul configuration
      template:
        src: consul.hcl.j2
        dest: "{{ consul_root_dir }}/etc/consul.hcl"
        owner: root
        group: "{{ consul_user }}"
        mode: 0640
        backup: True
      register: consul_main_conf
      notify: restart consul

    - name: Deploy consul reloadable configuration
      template:
        src: reload.hcl.j2
        dest: "{{ consul_root_dir }}/etc/reload.hcl"
        owner: root
        group: "{{ consul_user }}"
        mode: 0640
        backup: True
      register: consul_reload_conf
      notify: reload consul

    - name: Validate configuration
      command: consul validate {{ consul_root_dir }}/etc
      changed_when: False
      become_user: "{{ consul_user }}"
      register: consul_conf_validation

  rescue:
    - block:
        - name: Restore main configuration
          copy:
            src: "{{ consul_main_conf.backup_file }}"
            dest: "{{ consul_root_dir }}/etc/consul.hcl"
            remote_src: True
            owner: root
            group: "{{ consul_user }}"
            mode: 0640
          when: consul_main_conf.backup_file is defined
  
        - name: Restore reloadable configuration
          copy:
            src: "{{ consul_reload_conf.backup_file }}"
            dest: "{{ consul_root_dir }}/etc/reload.hcl"
            remote_src: True
            owner: root
            group: "{{ consul_user }}"
            mode: 0640
          when: consul_reload_conf.backup_file is defined

  tags: consul

- name: Fail if configuration validation failed
  fail:
    msg: "Failed to validate configuration: {{ consul_conf_validation.stdout }}"
  when: consul_conf_validation.rc != 0
  tags: consul

# Now we remove the backup config to prevent consul warning about invalid config files
- name: List backup conf
  shell: ls -1 {{ consul_root_dir }}/etc/*.hcl.*
  failed_when: False
  changed_when: False
  register: consul_backup_configs
  tags: consul

- name: Remove backup configs
  file: path={{ item }} state=absent
  loop: "{{ consul_backup_configs.stdout_lines }}"
  tags: consul
