---
- name: Generate the templates
  include_tasks: generate-templates.yml
  when:
  - openshift_openstack_stack_state == 'present'

- name: check for openstack client
  command: openstack
  register: openstack_cli_exists
  ignore_errors: True

- name: validate the Heat template
  command: openstack orchestration template validate -t {{ stack_template_path }}
  register: template_validation_output
  when: openstack_cli_exists|succeeded

- name: Check if the stack exists
  command: openstack stack show {{ openshift_openstack_stack_name }}
  ignore_errors: True
  register: stack_exists
  when: openstack_cli_exists|succeeded

- name: Dry-run the stack (create)
  command: openstack stack create --dry-run -t {{ stack_template_path }} {{ openshift_openstack_stack_name }}
  ignore_errors: True
  register: stack_create_dry_run_output
  when:
  - openstack_cli_exists|succeeded
  - stack_exists|failed

- name: Dry-run the stack (update)
  command: openstack stack update --dry-run -t {{ stack_template_path }} {{ openshift_openstack_stack_name }}
  ignore_errors: True
  register: stack_update_dry_run_output
  when:
  - openstack_cli_exists|succeeded
  - stack_exists|succeeded

- name: Show the dry run errors (create)
  debug: var=stack_create_dry_run_output.stderr
  when:
  - openstack_cli_exists|succeeded
  - stack_create_dry_run_output|failed

- name: Show the dry run errors (update)
  debug: var=stack_update_dry_run_output.stderr
  when:
  - openstack_cli_exists|succeeded
  - stack_update_dry_run_output|failed

- fail:
    msg: The Heat stack creation failed. Please inspect the message above.
  when:
  - openstack_cli_exists|succeeded
  - (stack_create_dry_run_output|failed or stack_update_dry_run_output|failed)

- name: Handle the Stack (create/delete)
  ignore_errors: True
  register: stack_create
  os_stack:
    name: "{{ openshift_openstack_stack_name }}"
    state: "{{ openshift_openstack_stack_state }}"
    template: "{{ stack_template_path | default(omit) }}"
    wait: yes

- name: get errors in stack creation, if any
  command: openstack stack failures list {{ openshift_openstack_stack_name }}
  register: stack_create_failures
  when:
  - openstack_cli_exists|succeeded
  - stack_create|failed

- name: show errors in stack creation, if any
  debug: var=stack_create_failures
  when:
  - openstack_cli_exists|succeeded
  - stack_create|failed

- fail:
    msg: Stack creation failed
  when:
  - stack_create|failed

- name: Add the new nodes to the inventory
  meta: refresh_inventory

- name: CleanUp
  include_tasks: cleanup.yml
  when:
  - openshift_openstack_stack_state == 'present'

# TODO(shadower): create the registry and PV Cinder volumes if specified
# and include the `prepare-and-format-cinder-volume` tasks to set it up
