---

- name: "Check if project <<{{ project.project_attributes.project_name }}>> exists"
  delegate_to: 127.0.0.1
  become: false
  uri:
    url: "{{ harbor_external_url }}/api/v2.0/projects/{{ project.project_attributes.project_name }}"
    user: '{{ harbor_admin_username }}'
    password: '{{ harbor_admin_password }}'
    method: GET
    body_format: json
    force_basic_auth: yes
    headers:
      Content-Type: application/json
    status_code: [200,403]
  register: project_exists
  delay: 10
  retries: 3

- name: "DEBUG"
  debug:
    msg: 'found projects: {{ project_exists.json }}'
  when: debug

- name: "Create project: <<{{ project.project_attributes.project_name }}>>"
  delegate_to: 127.0.0.1
  become: false
  uri:
    url: "{{ harbor_external_url }}/api/v2.0/projects"
    user: '{{ harbor_admin_username }}'
    password: '{{ harbor_admin_password }}'
    method: POST
    body_format: json
    body: '{{ project.project_attributes | to_json }}'
    force_basic_auth: yes
    headers:
      Content-Type: application/json
    status_code: [200,201]
  register: create_project
  delay: 10
  retries: 3
  until: create_project.status in [200,201]
  when: 
    - project_exists.status in [403]

- name: "Update project: <<{{ project.project_attributes.project_name }}>>"
  delegate_to: 127.0.0.1
  become: false
  uri:
    url: "{{ harbor_external_url }}/api/v2.0/projects/{{ project.project_attributes.project_name }}"
    user: '{{ harbor_admin_username }}'
    password: '{{ harbor_admin_password }}'
    method: PUT
    body_format: json
    body: '{{ project.project_attributes | to_json }}'
    force_basic_auth: yes
    headers:
      Content-Type: application/json
    status_code: [200,201]
  register: update_project
  delay: 10
  retries: 3
  until: update_project.status in [200,201]
  when: 
    - project_exists.status in [200]

- name: "Delete project: <<{{ project.project_attributes.project_name }}>>"
  delegate_to: 127.0.0.1
  become: false
  uri:
    url: "{{ harbor_external_url }}/api/v2.0/projects/{{ project.project_attributes.project_name }}"
    user: '{{ harbor_admin_username }}'
    password: '{{ harbor_admin_password }}'
    method: DELETE
    body_format: json
    force_basic_auth: yes
    headers:
      Content-Type: application/json
    status_code: [200]
  register: create_project
  delay: 10
  retries: 3
  until: create_project.status in [200]
  when:
    - project_exists.status in [200]
    - project.project_state == 'absent'
