---
- name: Check if the MAAS admin user was created
  stat:
    path: ~/.config/.maas-admin-created
  register: maas_admin_status

- name: Determine whether or not MAAS should be re-initialized
  set_fact:
    maas_should_init: "{{ not maas_admin_status.stat.exists or reinstall_maas_database }}"

- name: Initialize the MAAS region+rack
  become: true
  expect:
    command: '{{ maas_binary }} init region+rack --database-uri "postgres://{{ maas_database_username }}\
      :{{ maas_database_password }}@{{ maas_database_host }}/{{ maas_database_name }}"'
    responses:
      (.*)MAAS URL(.*): ""
      (.*)Are you sure you want to initialize again(.*): "Y"
    timeout: 300
  when: maas_should_init | bool

- name: Create the MAAS admin user
  become: true
  command: "{{ maas_binary }} createadmin --username={{ maas_admin_username }} --password={{ maas_admin_password }} --email={{ maas_admin_email }}"
  when: maas_should_init | bool

- name: Touch a file in ~/.config that will prevent the admin from being created again
  file:
    mode: 0400
    path: ~/.config/.maas-admin-created
    state: touch

- name: Fetch MAAS API key for admin user
  command: "{{ maas_binary }} apikey --username={{ maas_admin_username }}"
  changed_when: false
  register: maas_api_key_command

- name: Perform authenticated tasks
  block:
    - name: Login to MAAS using the API key
      become: true
      command: "{{ maas_binary }} login {{ maas_admin_username }} https://{{ maas_fqdn }}/MAAS/ {{ maas_api_key_command.stdout }}"
      changed_when: "{{ 'You are now logged in to the MAAS server' in maas_login_command.stdout }}"
      register: maas_login_command
  always:
    - name: Ensure admin user is logged out
      become: true
      command: "{{ maas_binary }} logout {{ maas_admin_username }}"
