# Copyright (c) 2019 Dell Inc. or its subsidiaries. All Rights Reserved.
---
- block:
  - name: "Generate random password"
    ngci_pass_gen:
      chars: ["digits", "lowercasealpha", "uppercasealpha"]
    register: random_password
    no_log: "{{ enforce_no_log }}"

  - name: Set users fact
    set_fact:
      user_password: "{{ random_password.generated_password }}"
    no_log: "{{ enforce_no_log }}"
  when: tower_user_info.password is undefined

- name: Set default password if exists
  set_fact:
    user_password: "{{ tower_user_info.password }}"
  no_log: "{{ enforce_no_log }}"
  when: tower_user_info.password is defined

- name: Fetch users organization Id
  set_fact:
    org_id: "{{ organization_list | selectattr('name', 'match', tower_user_info.target_org) | map(attribute='id') | list }}"

- name: Build payload to add tower user
  set_fact:
    add_user_body: '{"username":"{{ tower_user_info.username }}","first_name":"{{ tower_user_info.fname }}","last_name":"{{ tower_user_info.lname }}","email":"{{ tower_user_info.email }}","is_superuser":"{{ tower_user_info.is_superuser | bool }}","is_system_auditor":"{{ tower_user_info.is_system_auditor | bool }}","password":"{{ user_password }}"}'
  no_log: "{{ enforce_no_log }}"

- name: "Add tower user - {{ tower_user_info.username }}"
  shell: >
    kubectl exec -it -n ngci-consul {{ consul_pod_name.stdout }} -c ngci-secret-storage-consul --
    curl -XPOST -u {{ awx_admin_username }}:{{ awx_admin_password }} {{ awx_service_address }}/api/v2/organizations/{{ org_id.0 }}/users/ 
    -H 'Content-Type: application/json' -d '{{ add_user_body | to_json }}'
  register: add_user_resp
  no_log: "{{ enforce_no_log }}"

- name: Add user json resp
  set_fact:
    add_user_json: "{{ add_user_resp.stdout | from_json }}"

- name: Check if user already exists
  set_fact:
    user_already_exists: "{{ add_user_resp.stdout is search('A user with that username already exists') }}"

- block:
  - name: Retrieve user id
    set_fact:
      user_id: "{{ add_user_json.id }}"

  - name: Retrieve role id 
    set_fact:
      role_id: "{{ roles_list | selectattr('name', 'match', tower_user_info.target_org_role) | selectattr('summary_fields.resource_name', 'match', tower_user_info.target_org) |map(attribute='id') | list }}"

  - name: "Add role for tower user - {{ tower_user_info.username }} in organization - {{ tower_user_info.target_org }}"
    shell: >
      kubectl exec -it -n ngci-consul {{ consul_pod_name.stdout }} -c ngci-secret-storage-consul --
      curl -XPOST -u {{ awx_admin_username }}:{{ awx_admin_password }} {{ awx_service_address }}/api/v2/users/{{ user_id }}/roles/ 
      -H 'Content-Type: application/json' -d '{"id": {{ role_id.0 }} }'
    no_log: "{{ enforce_no_log }}" 
  
  - import_tasks: update-vault.yml
    when: tower_user_info.password is undefined
  
  when: not user_already_exists