---
# file: roles/minio/tasks/minio_users.yml

- name: "handle secret {{ ansible_hostname }}/minio_{{ minio_user }}_password"
  block:
    - name: "get {{ ansible_hostname }}/minio_{{ minio_user }}_password from hashicorp vault"
      ansible.builtin.set_fact:
        "minio_{{ minio_user | replace('-', '_') | replace('.', '_') }}_password": "{{ lookup('hashi_vault', 'secret=talas-kv/data/' + host_vars_location + '/' + ansible_hostname)['minio_' + minio_user + '_password'] }}"
  rescue:
    - name: "generate a random password for {{ ansible_hostname }}/minio_{{ minio_user }}_password"
      ansible.builtin.set_fact:
        password: "{{ lookup('password','/dev/null chars=ascii_letters,digits length=50') }}"
    - name: "patching hashicorp vault with generated minio_{{ minio_user }}_password"
      ansible.builtin.command: "vault kv patch talas-kv/{{ host_vars_location }}/{{ ansible_hostname }} minio_{{ minio_user }}_password={{ password }}"
      delegate_to: localhost
      become: false
      register: result
      ignore_errors: true
    - name: "patch failed because the entry doesn't exist, creating it instead"
      ansible.builtin.command: "vault kv put talas-kv/{{ host_vars_location }}/{{ ansible_hostname }} minio_{{ minio_user }}_password={{ password }}"
      delegate_to: localhost
      become: false
      when:
        - result.failed
        - '"No value found" in result.stderr'
    - name: "assign password value to minio_{{ minio_user }}_password"
      set_fact:
        "minio_{{ minio_user | replace('-', '_') | replace('.', '_') }}_password": "{{ password }}"

- name: "Check if user can connect to minio"
  ansible.builtin.shell: "MC_HOST_myalias=http://{{ minio_user }}:\"{{  hostvars[inventory_hostname]['minio_' + minio_user | replace('-', '_') | replace('.', '_') + '_password'] }}\"@localhost:{{ minio_port }} mcli ls myalias/nonexistingbucket --json"
  register: check_user
  failed_when: false
  changed_when: false
  check_mode: false

- name: "add user {{ minio_user }} or update its password"
  ansible.builtin.command: "mcli admin user add minio_on_localhost {{ minio_user }} {{ hostvars[inventory_hostname]['minio_' + minio_user | replace('-', '_') | replace('.', '_') + '_password'] }} --json"
  register: add_user
  failed_when: "'success' not in add_user.stdout|from_json|json_query('status')"
  when: "('InvalidAccessKeyId' == check_user.stdout | from_json | json_query('error.cause.error.Code')) or ('SignatureDoesNotMatch' == check_user.stdout|from_json|json_query('error.cause.error.Code'))"
