- name: Determine architecture
  set_fact:
    consul_template_arch: "{{ arch_mapping[ansible_architecture] | default('amd64') }}"

- name: Download consul-template checksum file
  get_url:
    url: "https://releases.hashicorp.com/consul-template/{{ consul_template.version }}/consul-template_{{ consul_template.version }}_SHA256SUMS"
    dest: "/tmp/consul-template_{{ consul_template.version }}_SHA256SUMS"
    mode: '0644'

- name: Extract expected checksum
  shell: |
    grep "consul-template_{{ consul_template.version }}_linux_{{ consul_template_arch }}.zip" \
      /tmp/consul-template_{{ consul_template.version }}_SHA256SUMS | cut -d' ' -f1
  register: expected_checksum
  changed_when: false

- name: Install consul-template
  unarchive:
    src: "https://releases.hashicorp.com/consul-template/{{ consul_template.version }}/consul-template_{{ consul_template.version }}_linux_{{ consul_template_arch }}.zip"
    dest: "{{ consul_template.install_dir }}"
    remote_src: yes
    owner: root
    group: root
    mode: '0755'
    checksum: "sha256:{{ expected_checksum.stdout }}"

- name: Create consul-template user
  user:
    name: "{{ consul_template.user }}"
    group: "{{ consul_template.group }}"
    system: yes
    shell: /bin/false
    home: "{{ consul_template.config_dir }}"
    create_home: no

- name: Create consul-template group
  group:
    name: "{{ consul_template.group }}"
    system: yes

- name: Create consul-template directories
  file:
    path: "{{ item.path }}"
    state: directory
    mode: "{{ item.mode }}"
    owner: "{{ item.owner | default('root') }}"
    group: "{{ item.group | default('root') }}"
  loop:
    - { path: "{{ consul_template.config_dir }}", mode: '0755', owner: "{{ consul_template.user }}", group: "{{ consul_template.group }}" }
    - { path: "{{ certificate_paths.cert_dir }}", mode: '0755' }
    - { path: "{{ certificate_paths.private_dir }}", mode: '0700' }

- name: Deploy consul-template template files
  copy:
    src: "{{ item }}"
    dest: "{{ consul_template.config_dir }}/{{ item }}"
    mode: '0644'
    owner: "{{ consul_template.user }}"
    group: "{{ consul_template.group }}"
  loop:
    - certificate.ctmpl
    - private_key.ctmpl
    - chain_pem.ctmpl
  notify: restart consul-template

- name: Deploy consul-template config
  template:
    src: consul-template-config.hcl.j2
    dest: "{{ consul_template.config_dir }}/config.hcl"
    mode: '0600'
    owner: "{{ consul_template.user }}"
    group: "{{ consul_template.group }}"
  notify: restart consul-template

- name: Deploy consul-template systemd unit
  template:
    src: consul-template.service.j2
    dest: /etc/systemd/system/consul-template.service

- name: Enable and start consul-template
  systemd:
    name: consul-template
    enabled: true
    state: started
    daemon_reload: yes
