---
# file: roles/postgres/tasks/users.yml

# We replace '-' by '_' only in the ansible var postgres_user_{{ user.name }}_password, not in hashicorp vault
- name: "handle secret {{ ansible_hostname }}/postgres_user_{{ user.name | replace('-', '_') }}_password"
  block:
    - name: "get {{ ansible_hostname }}/postgres_user_{{ user.name | replace('-', '_') | replace('.', '_') }}_password from hashicorp vault"
      set_fact:
        "postgres_user_{{ user.name | replace('-', '_') | replace('.', '_') }}_password": "{{ lookup('hashi_vault', 'secret=talas-kv/data/' + host_vars_location + '/' + ansible_hostname)['postgres_user_' ~ user.name ~ '_password'] }}"
  rescue:
    - name: "generate a random password for {{ ansible_hostname }}/postgres_user_{{ user.name | replace('-', '_') | replace('.', '_') }}_password"
      set_fact:
        password: "{{ lookup('password','/dev/null chars=ascii_letters,digits length=50') }}"
    - name: "patching hashicorp vault with generated postgres_user_{{ user.name | replace('-', '_') | replace('.', '_') }}_password"
      delegate_to: localhost
      become: False
      command: "vault kv patch talas-kv/{{ host_vars_location }}/{{ ansible_hostname }} postgres_user_{{ user.name }}_password={{ password }}"
      register: result
      ignore_errors: True
    - name: "patch failed because the entry doesn't exist, creating it instead"
      delegate_to: localhost
      become: False
      command: "vault kv put talas-kv/{{ host_vars_location }}/{{ ansible_hostname }} postgres_user_{{ user.name }}_password={{ password }}"
      when:
        - result.failed
        - '"No value found" in result.stderr'
    - name: "assign password value to postgres_user_{{ user.name | replace('-', '_') | replace('.', '_') }}_password"
      set_fact:
        "postgres_user_{{ user.name | replace('-', '_') | replace('.', '_') }}_password": "{{ password }}"
  when:
    - user.password is defined
    - user.password == "auto"
  tags: postgres

- name: "role {{ user.name }}"
  become: True
  become_user: postgres
  become_method: sudo
  postgresql_user:
    user: "{{ user.name }}"
    password: "{% if user.password is defined and user.password == 'auto' %}{{ vars['postgres_user_' +  user.name | replace('-', '_') | replace('.', '_')  + '_password'] }}{% else %}{{ user.password | default(omit) }}{% endif %}"
    role_attr_flags: "{{ user.attrib | default(omit) }}"
    conn_limit: "{{ user.conn_limit | default(omit) }}"
  environment:
    PGOPTIONS: "{{ pg_role_options | default(None) }}"
  tags: postgres

- name: "role {{ user.name }} groups : {{ user.groups }}"
  become: true
  become_user: postgres
  become_method: sudo
  postgresql_membership:
    user: "{{ user.name }}"
    groups: "{{ user.groups }}"
  when: user.groups is defined
  tags: postgres
