---
- name: "Check if project <{{ project_name }}> exists"
  delegate_to: 127.0.0.1
  become: false
  uri:
    url: "{{ shared_service_url_harbor }}/api/v2.0/projects/{{ 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,404]
  register: project_exists

- name: "Check if project <{{ project_name }}> exists"
  debug:
    msg: '{{ project_exists.json }}'
  when: debug

- name: "Create project <{{ project_name }}>"
  delegate_to: 127.0.0.1
  become: false
  uri:
    url: "{{ shared_service_url_harbor }}/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: project_create
  when:
    - project_exists.status in [404]
    - project.project_state == 'present'

- name: "Create project <{{ project_name }}>"
  debug:
    msg: '{{ project_create.json }}'
  when:
    - debug
    - project_exists.status in [404]
    - project.project_state == 'present'

- name: "Update project <{{ project_name }}>"
  delegate_to: 127.0.0.1
  become: false
  uri:
    url: "{{ shared_service_url_harbor }}/api/v2.0/projects/{{ 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: project_update
  when:
    - project_exists.status in [200]
    - project.project_state == 'present'

- name: "Update project <{{ project_name }}>"
  debug:
    msg: '{{ project_update.json }}'
  when:
    - debug
    - project_exists.status in [200]
    - project.project_state == 'present'

- name: "Delete project <{{ project_name }}>"
  delegate_to: 127.0.0.1
  become: false
  uri:
    url: "{{ shared_service_url_harbor }}/api/v2.0/projects/{{ 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: project_delete
  when:
    - project_exists.status in [200]
    - project.project_state == 'absent'

- name: "Delete project <{{ project_name }}>"
  debug:
    msg: '{{ project_update.json }}'
  when:
    - debug
    - project_exists.status in [200]
    - project.project_state == 'absent'
