---
- name: Deprecation message for network isolation types
  debug:
    msg: >-
      Network isolation type 'multi-nic' is deprecated in R release,
      please use 'multiple-nics'.
  when: network_isolation_type == 'multi-nic'

- name: Ensure local working dir exists
  file:
    path: "{{ local_working_dir }}"

- name: Clone Openstack Virtual Baremetal repo if it does not exist
  git:
    repo: https://git.openstack.org/openstack/openstack-virtual-baremetal.git
    dest: "{{ local_working_dir }}/openstack-virtual-baremetal"
    version: "{{ ovb_repo_version }}"

- include: ovb-cleanup-stacks-keypairs.yml
  when: cleanup_stacks_keypairs|bool

- name: generate idnum for all run-related entities
  set_fact:
    idnum: "{{ tmp.idnum }}"

- name: set fact for undercloud image
  set_fact:
    latest_undercloud_image: "{{ latest_guest_image[osp_release | default(release)] }}"

- name: copy key inserted in image to undercloud_key location
  copy:
    src: "{{ existing_key_location }}{{ item }}"
    dest: "{{ local_working_dir }}/id_rsa_undercloud{{ item }}"
    mode: 0600
  with_items:
    - ""
    - .pub

- name: Copy deploy stack parameters template
  template:
    src: env.yaml.j2
    dest: "{{ local_working_dir }}/env-{{ idnum }}.yaml"
    mode: 0755

- name: Add keypair
  shell: >
      export OS_USERNAME="{{ os_username }}";
      export OS_PASSWORD="{{ os_password }}";
      export OS_TENANT_NAME="{{ os_tenant_name }}";
      export OS_AUTH_URL="{{ os_auth_url }}";
      nova keypair-add --pub-key {{ existing_key_location }}.pub key-{{ idnum }}
  ignore_errors: true
  no_log: true

- name: copy clouds.yaml file
  template:
    src: clouds.yaml.j2
    dest: "{{ local_working_dir }}/clouds.yaml"
    mode: 0755

- name: Deploy stack
  shell: >
      export OS_CLIENT_CONFIG_FILE="{{ local_working_dir }}/clouds.yaml";
      export OS_CLOUD="{{ cloud_name }}";
      {{ ovb_dir }}/bin/deploy.py --env {{ local_working_dir }}/env-{{ idnum }}.yaml --name {{ stack_name }} --quintupleo
  args:
    chdir: "{{ ovb_dir }}"

- name: Return stack state
  shell: >
      export OS_USERNAME="{{ os_username }}";
      export OS_PASSWORD="{{ os_password }}";
      export OS_TENANT_NAME="{{ os_tenant_name }}";
      export OS_AUTH_URL="{{ os_auth_url }}";
      export STACK_LOG="{{ local_working_dir }}/ovb_create_stack.log";
      export COUNTER=0;
      while ! openstack stack show {{ stack_name }} | grep CREATE_COMPLETE; do
        if [ $COUNTER -lt 10 ]; then
          sleep 30;
          if openstack stack show {{ stack_name }} | grep FAILED ; then
            echo "Failed OVB stack" > $STACK_LOG;
            openstack stack show {{ stack_name }} >> $STACK_LOG 2>&1;
            openstack stack failures list --long {{ stack_name }} >> $STACK_LOG 2>&1 || echo 'Failed to list stack failures' >> $STACK_LOG;
            exit 0;
          fi;
          COUNTER=$((COUNTER+1));
        fi;
      done;
      openstack stack show "{{ stack_name }}" | grep "status"
  register: stack_status
  no_log: true

- name: Show stack status
  debug:
    var: stack_status.stdout_lines

- block:
    - name: Get full stack status info in case of failure
      shell: openstack stack show "{{ stack_name }}"
      register: failed_stack

    - name: Show stack status in case of failure
      debug: var="failed_stack.stdout"

    - name: Fail if stack did not deploy successfully
      fail:
        msg: "Stack {{ stack_name }} did not deploy successfully. See the stack status message above."
  when: stack_status.stdout.find("CREATE_COMPLETE") == -1

- name: Return floating ip outputs
  shell: >
      export OS_USERNAME="{{ os_username }}";
      export OS_PASSWORD="{{ os_password }}";
      export OS_TENANT_NAME="{{ os_tenant_name }}";
      export OS_AUTH_URL="{{ os_auth_url }}";
      openstack stack show {{ stack_name }} -f json -c outputs
  register: stack_outputs
  no_log: true

- name: Set fact for undercloud floating IP address
  set_fact:
    undercloud_ip: "{{ (stack_outputs.stdout|from_json).outputs[0].output_value }}"
    cacheable: true

- name: Add provisioned undercloud host
  add_host:
    name: undercloud
    hostname: "{{ undercloud_ip }}"
    groups: "{{ node_groups| join(',') }}"
    ansible_host: "{{ undercloud_ip }}"
    ansible_user: root
    ansible_fqdn: undercloud
    ansible_private_key_file: "{{ undercloud_key }}"
    ansible_ssh_extra_args: "{{ ssh_extra_args }}"
    undercloud_ip: "{{ undercloud_ip }}"

- name: Wait for provisioned host to become reachable
  command: |
    ssh -o BatchMode=yes -o "StrictHostKeyChecking=no" root@{{ undercloud_ip }} -i "{{ undercloud_key }}"
  register: result
  until: result is success
  retries: 300
  delay: 5

- when: ovb_setup_user|default('false')|bool
  block:

    - name: Setup user
      user:
        name: "{{ nodepool_user }}"
        groups: wheel
        append: true
      become: true
      delegate_to: undercloud

    - name: Setup keys
      authorized_key:
        user: "{{ nodepool_user }}"
        state: present
        key: "{{ lookup('file', '{{ undercloud_key }}.pub') }}"
      become: true
      become_user: "{{ nodepool_user }}"
      delegate_to: undercloud

    - name: Allow user to have passwordless sudo
      lineinfile:
        dest: /etc/sudoers
        state: present
        line: '{{ nodepool_user }} ALL=(ALL) NOPASSWD:ALL'
        validate: 'visudo -cf %s'
      become: true
      delegate_to: undercloud

    - name: Add undercloud with non-root user
      add_host:
        name: subnode-0
        hostname: "{{ undercloud_ip }}"
        groups: subnodes
        ansible_user: "{{ nodepool_user }}"
        ansible_host: "{{ undercloud_ip }}"
        ansible_private_key_file: "{{ undercloud_key }}"
        subnode_public_ip: "{{ undercloud_ip }}"
        subnode_private_ip: 192.168.23.23

- name: Build nodes.json file to be used as instackenv.json
  shell: >
      chdir={{ local_working_dir }}
      export OS_CLIENT_CONFIG_FILE="{{ local_working_dir }}/clouds.yaml";
      export OS_CLOUD="{{ cloud_name}}";
      {{ ovb_dir }}/bin/build-nodes-json --env {{ local_working_dir }}/env-{{ idnum }}.yaml --driver {{ baremetal_driver }}
  register: nodes_json

- name: remove clouds.yaml file
  file:
    path: "{{ local_working_dir }}/clouds.yaml"
    state: absent

- name: Dump hosts to file
  template:
    src: ovb_hosts.j2
    dest: '{{ local_working_dir }}/ovb_hosts'
  when: ovb_dump_hosts|default('false')|bool
