---
- name: Create workspace directory if not exists
  file:
    path: "{{ paas_ci_workdir }}"
    state: directory

- name: Get template
  get_url:
    url: "{{ paas_ci_test.template_url }}"
    dest: "{{ paas_ci_workdir + '/template.yaml' }}"  

- name: Deployment command
  set_fact:
    depcreate_cmd: "orchent depcreate --ojson template.yaml -g {{ paas_ci_iam_group }} {{ paas_ci_test.inputs }}"

- debug:
    var: depcreate_cmd

- name:  Create the deployment
  command: "{{ depcreate_cmd }}"
  args:
    chdir: "{{ paas_ci_workdir }}"
  register: depcreate_output

- debug:
    var: depcreate_output

- set_fact:
    deployment: "{{ depcreate_output.stdout|from_json }}"

- name: Save preliminary deployment info to file
  copy:
    dest: "{{ paas_ci_workdir }}/dep.json"
    content: "{{ deployment }}"

- debug:
    var: deployment

- name: Sleep for 5 mins and timeout
  wait_for:
    delay: 300
    timeout: 0

- name:  Check the deployment status (every 1 minute)
  command: orchent depshow --ojson "{{ deployment.uuid }}"
  register: depshow_output
  until: "'PROGRESS' not in depshow_output.stdout"
  retries: "{{ paas_ci_test.n_timeout_ticks }}"
  delay: 60
  failed_when: "'error' in depshow_output.stdout"
  ignore_errors: true

- name: Save result to file
  copy:
    dest: "{{ paas_ci_workdir }}/dep.json"
    content: "{{ depshow_output.stdout }}"

- name: Retrieve depshow from deployment
  command: orchent depshow --verbose "{{ deployment.uuid }}"
  register: depshow_verbose_output

- name: Save depshow to file
  copy:
    dest: "{{ paas_ci_workdir }}/depshow_deployment.txt"
    content: "{{ depshow_verbose_output.stdout }}"

- name: Retrieve deplog from deployment
  command: orchent deplog "{{ deployment.uuid }}"
  register: deplog_output

- name: Save deplog to file
  copy:
    dest: "{{ paas_ci_workdir }}/deplog_deployment.txt"
    content: "{{ deplog_output.stdout }}"

- set_fact:
    deployment: "{{ depshow_output.stdout|from_json }}"

- name: Get deployment status and outputs (if successful)
  assert:
    that:
      - deployment.status == 'CREATE_COMPLETE'
    fail_msg: "TEST FAILED -  deployment uuid: {{ deployment.uuid }}, status: {{ deployment.status }}"
    success_msg: "TEST PASSED - deployment uuid: {{ deployment.uuid }}, status: {{ deployment.status }}, outputs: {{ deployment.outputs }}"