---

- name: Install needed tools
  package:
    name:
      - tar
      - zstd
      - unzip
      - jq
  tags: vault

- when: vault_install_mode != 'none'
  block:
    - name: Download vault
      get_url:
        url: "{{ vault_archive_url }}"
        dest: "{{ vault_root_dir }}/tmp"
        checksum: sha256:{{ vault_archive_sha256 }}

    - name: Extract the archive
      unarchive:
        src: "{{ vault_root_dir }}/tmp/vault_{{ vault_version }}_linux_amd64.zip"
        dest: "{{ vault_root_dir }}/tmp"
        remote_src: True

    - name: Install vault binary
      copy:
        src: "{{ vault_root_dir }}/tmp/vault"
        dest: "{{ vault_root_dir }}/bin/vault"
        remote_src: True
        mode: 755
      notify: restart vault

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

  tags: vault

- name: Install bash completion support
  copy:
    content: |
      complete -C {{ vault_root_dir }}/bin/vault vault
    dest: /etc/bash_completion.d/vault
    mode: 0644
  tags: vault

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

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

- name: Reload systemd
  systemd: daemon_reload=True
  when: vault_unit.changed or vault_secrets_nomad_unit.changed
  tags: vault

- name: Install dehydrated hook
  template: src=dehydrated_hook.j2 dest=/etc/dehydrated/hooks_deploy_cert.d/vault mode=755
  tags: vault

- name: Install profile script
  copy:
    content: |
      #!/bin/sh
      export VAULT_ADDR={{ vault_conf.api_addr }}
    dest: /etc/profile.d/vault.sh
    mode: 0755
  tags: vault

